1
2//place where you will send
3import { useHistory } from "react-router-dom";
4
5const history = useHistory();
6history.push({
7 pathname: "/home",
8 state: {name : 'demo'},
9});
10
11//place where you will get data
12import { useLocation } from 'react-router';
13
14const location = useLocation();
15console.log(location.state);
16
17
1// Imagine the directory structure of the app as follows:
2// The parent component actually renders the child components in the app.
3
4App
5 └── Parent
6 ├── Child
7 └── Child2
8
9// Parent Component: Functional Component
10const Parent = () => {
11 const [data, setData] = useState('');
12
13 const parentToChild = () => {
14 setData('This is data from Parent Component to the Child Component.');
15 };
16
17 return (
18 <div className="App">
19 <Child parentToChild={data}/>
20
21 <div>
22 <Button primary onClick={() => parentToChild()}>
23 Click Parent
24 </Button>
25 </div>
26 </div>
27 );
28};
29
30// Child Component: Functional Component
31const Child = (parentToChild) => {
32 return (
33 <div>
34 {parentToChild}
35 </div>
36 )
37}
38
39// Parent Component: Class Component
40class Parent extends React.Component {
41 state = { data: 'Hello World' };
42 render() {
43 return (
44 <div>
45 <Child /> //no data to send
46 <Child2 dataFromParent={this.state.data} />
47 </div>
48 );
49 }
50}
51
52// Child2 Component: Class Component
53// Use the variable this.props.dataFromParent
54// to obtain the data passed from parent to child.
55class Child2 extends React.Component {
56 render() {
57 return <div>Data from parent is:{this.props.dataFromParent}</div>;
58 }
59}
60
61