pass data to component react
// Imagine the directory structure of the app as follows:
// The parent component actually renders the child components in the app.
App
└── Parent
├── Child
└── Child2
// Parent Component: Functional Component
const Parent = () => {
const [data, setData] = useState('');
const parentToChild = () => {
setData('This is data from Parent Component to the Child Component.');
};
return (
<div className="App">
<Child parentToChild={data}/>
<div>
<Button primary onClick={() => parentToChild()}>
Click Parent
</Button>
</div>
</div>
);
};
// Child Component: Functional Component
const Child = (parentToChild) => {
return (
<div>
{parentToChild}
</div>
)
}
// Parent Component: Class Component
class Parent extends React.Component {
state = { data: 'Hello World' };
render() {
return (
<div>
<Child /> //no data to send
<Child2 dataFromParent={this.state.data} />
</div>
);
}
}
// Child2 Component: Class Component
// Use the variable this.props.dataFromParent
// to obtain the data passed from parent to child.
class Child2 extends React.Component {
render() {
return <div>Data from parent is:{this.props.dataFromParent}</div>;
}
}
Are there any code examples left?
New code examples in category Javascript