Passing variables and functions among components in React JS
There are different ways of communication available to pass data between the components in react projects.
Method One: Using Call back functions & props
For passing data from parent to child component, we use props. Props data is sent by the parent component and cannot be changed by the child component as they are read-only.
//ComponentOne.js:
import React from ‘react’;
import ComponentTwo from “./mysystem/ComponentTwo.js”
const ComponentOne = () => {
varOne = Name;
varTwo = Age;
return
(
<div>
<ComponentTwo varOne={varOne} varTwo={varTwo}/>
</div>
)}
export default ComponentOne;
//ComponentTwo.js:
importReact
from
'react'
;
importComponentOne
from
'/mysystem/ComponentOne.js'
;
constComponentTwo
= (
props) => {
return
<div>
<p>{props.varOne}, {props.varTwo}</p>
</div>
exportdefault
ComponentTwo;
Method Two: Using React Hooks
React hooks such as useHistory, useNavigate
can be used to push the new route from parent component and pass the state object as the second argument for the child component.
In the receiving component, useLocation hook is used to access the state object and retrieve the passed data.
//ComponentOne.js:
import {useHistory} from ‘react-router-dom’;
const ComponentOne = () = > {
const history = useHistory();
const data ={ name: “John”, age: 30};
const handleClick = () => {
history.push({pathname:”/componentTwo”, state: data});
};
return <button onClick={handleClick}>Go to ComponentTwo</button>;
};
export default ComponentOne;
//ComponentTwo.js:
import {useLocation} from “react-rouer-dom”;
const ComponentTwo = () => {
const location = useLocation();
const data = location.state;
return (
<div>
<p> Name : {data.name} </p>
<p> Age : {data.age} </p>
</div>
);
};
export default ComponentTwo;