Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refreshing children state from parent React

I have a table with some data and each element in the table is a React class component. It looks like this:

Table

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.

like image 550
Tomasz Kasperek Avatar asked Apr 24 '15 13:04

Tomasz Kasperek


People also ask

How do you pass the state from parent to child in React?

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 .

How do you refresh a React state?

import React from 'react'; function App() { function refreshPage() { window. location. reload(false); } return ( <div> <button onClick={refreshPage}>Click to reload!

How do you update state in child component React?

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.

Can I call child function from parent React?

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.


1 Answers

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".

like image 105
Luca Pelosi Avatar answered Sep 20 '22 23:09

Luca Pelosi