I have a table with some data and each element in the table is a React class component. It looks like this:
All i want is to have one checkbox for "check all" feature (top left checkbox). The thing is I don't know how to solve that because of props
and state
.
I have code like that in single element component:
getInitialState: function() {
return { component: this.props.data };
},
render: function() {
var data = this.state.component;
data = data.set('checked', this.props.data.get('checked'));
...
}
And I know I shouldn't get checked
param from props
but it is just temporary.
What I have problem with is: When I update checked
param in parent it doesn't update state, because getInitialState
isn't called after refresh (yep, i know it should be like that).
My question is: can I somehow update state of child component? Or it is better way to achieve that.
To pass data from child to parent component in React:Pass a function as a prop to the Child component. Call the function in the Child component and pass the data as arguments. Access the data in the function in the Parent .
import React from 'react'; function App() { function refreshPage() { window. location. reload(false); } return ( <div> <button onClick={refreshPage}>Click to reload!
To update the parent state from the children component, either we can use additional dependencies like Redux or we can use this simple method of passing the state of the parent to the children and handling it accordingly.
To call a child's function from a parent component in React: Wrap the Child component in a forwardRef . Use the useImperativeHandle hook in the child to add a function to the Child . Call the Child's function from the Parent using the ref, e.g. childRef. current.
With functional components:
An easy way to refresh the children internal state when props provided by parent change is through useEffect()
:
In the children:
const [data, setData] = useState(props.data);
useEffect( () => {
setData(props.data);
}, [props.data]);
In this way everytime the props.data
change the useEffect will be triggered and force to set a new status for some data and therefore the component will "refresh".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With