Reputation: 10759
I have this child component that will end up in a parent component. I need to update the state or send data to the child one a function finishes in the parent ( a button in the parent is pushed.)
const SenViewer = (data) => {
const [sen, setSen] = useState({
sens: [],
});
this.setSen({ sens: data });
return (
<div>
{this.state.sens.map((user) => (
<Card className='text-center'>
<Card.Header>
Ticket: <p>Sen </p>
</Card.Header>
<Card.Body>
<Card.Title>
<p>Entire Audio</p>
</Card.Title>
<Card.Text>
Magnitude:
<p>{user.id}</p>
Score
<p>{user.total}</p>
</Card.Text>
</Card.Body>
<Card.Footer className='text-muted'>
<Button variant='primary'>TODO: smiley if good total</Button>
</Card.Footer>
</Card>
))}
</div>
);
}; // end of component
Here is the render for the parent.
<Parent>
<SenViewer />
</Parent>
Upvotes: 0
Views: 45
Reputation: 5834
In you parent component create a state, which will hold the data you want to send.
const Parent = () => {
const [data,setData] = React.useState({});
React.useEffect(()=> {
setData({name:'sd'});
},[setData]);
return <div>
<SenViewer data={data} />
</div>
}
In Child Component, use it like this
const SanViewer = (props)=> {
console.log(props.data) // received data from parent
}
Read more about props here https://reactjs.org/docs/components-and-props.html
Upvotes: 2
Reputation: 1074
You can pass the data to the child component via props. Also, you don't need to set that data again in the state of the child component, unless there is some stateful work that needs to be done within the child.
<Parent>
<SenViewer data={parentData} />
</Parent>
Here parentData
is something which <Parent />
manages, and now child can use that information to do what it needs to do.
A simple sample of the parent in this case would be,
const Parent = () => {
const [parentData, setParentData] = useState({});
return (
<div>
<button value='click me' onClick={() => setParentData({someData: 'foo'})}></button>
<SenViewer data={parentData} />
</div>
);
};
Upvotes: 1