How to set state of parent component from a child component in react?

update child state from parent react
pass data from child component to parent component react
pass state from child to parent react
update parent state from child react hooks
get state value from child component react
how to pass props from child to parent component
call child function from parent react
reload parent component from child component

I have a state in Parent Component that has an Array of patients. My Child Component 4 is a Countdown component (// countdown component renders individually countdown for each patient in the array) and when the countdown gets to <=0, I would like to reset the patient’s locationInfo & status value to be empty string in the patient array. In my parent component, I have resetPatient function that maps over the patient array and should set the values(locationInfo & status) of the patient that has <=0 counter to empty strings. The resetPatient function is passed as props down to my Countdown component(4). In Countdown component I call the this.props.resetPatient function when the counter gets to <=0. However, this is not working for me. The state on Parent Component doesn’t change.

Parent Component - Child Component 1 - Child Component 2 - Child Component 3 - Child Component 4

Parent component 

export default class ObservationWorkflow extends React.Component {


    constructor(props) {
        super(props);
       this.state = {

         patients = [
           { room: "1", name: 'John', locationInfo: 'TV', status: 'Awake'},
           { room: "2", name: 'Shawn, locationInfo: 'Toilet', status: 'Awake'},
           { room: "3", name: 'Gereth, locationInfo: 'Garden', status: 'Awake'}
          ]
         }
       this.resetPatient = this.resetPatient.bind(this);

 }


    resetPatient = (patient, index) => {

        this.setState(prevState => ({

            patients: prevState.patients.map((patient, i) => {
                if (i === index) {
                    return {
                        ...patient,
                        locationInfo: '', 
                        status: ''
                    };
                }
                return patient;
            }),
        }));
    }

   render() {
      return (
    <Child component(1)={this.resetPatient} // then child component 2 passes it down as props to 3 then 4. 
     )
   }
}

Countdown component(4)// countdown component renders individually countdown for each patient in the array. 

 export default class ObservationCountDown extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            obsTimeleft: undefined
        };

        this.countDown = this.countDown.bind(this);
        this.startCountdown = this.startCountdown.bind(this);
        this.countDownInterval = null;
    }

    countDown() {

        const { obsTakenTime, patient, index } = this.props; 
        const nextDueTimeForObs = moment(obsTakenTime).add(10, 'minutes'); 

        const nextObservationTime = nextDueTimeForObs.subtract(moment.now()).format('mm');

        if (obsTakenTime) {
            this.setState({ obsTimeleft: nextObservationTime + ' mins' });
        }
        if (Number(nextObservationTime) <= 1) {
            this.props.disablePatientUpdate();
        }
        if (Number(nextObservationTime) <= 0) {
            this.setState({ obsTimeleft: 'Overdue' });
            this.props.enablePatientUpdate();
            clearInterval(this.countDownInterval);

            () => this.props.resetPatient(patient, index); // here i call the function as call back
        }
    }

How to set the state of parent component from a child component in react.

It looks like you're not calling resetPatient, and that index isn't defined in that scope in any case.

I would add an id to your patient object and use this to identify which one needs to be reset:

 patients = [
       { id:1, room: "1", name: 'John', locationInfo: 'TV', status: 'Awake'},
       { id:2, room: "2", name: 'Shawn, locationInfo: 'Toilet', status: 'Awake'},
       { id:3, room: ... }]

and your resetPatient would become:

 resetPatient = (patient) => {

    this.setState(prevState => ({

        patients: prevState.patients.map(p => {
            if (patient.id === p.id) {
                return {
                    ...p,
                    locationInfo: '', 
                    status: ''
                };
            }
            return p;
        }),
    }));
}

Then you can just call:

   this.props.resetPatient(patient)

6.7 Accessing Children Components/Nodes · React Enlightenment , How do you access child component in parent component react? So let’s create the Parent component first. function Parent() { const [value, setValue] = React.useState(""); function handleChange(newValue) { setValue(newValue); } // We pass a callback to Child return <Child value={value} onChange={handleChange} />; } As you see that we set the onChange property to the Child component. Next step is to create the Child component.

First, you do not need anymore this.resetPatient = this.resetPatient.bind(this); when you are already using arrow function at resetPatient = (patient, index) => {...}

Second, pass your callback like this :

<Child resetPatient= { this.resetPatient } />

and then access it in child as props :

 this.props.resetPatient(..., ...)

Hope it helps

Change Parent Component State from Child using hooks in React , How do you update parent state from child component in react hooks? In the parent App component, add the following handleStateChange () method and bind it to the class: In the handleStateChange () method we grab the contacts state variable, we push the contact passed as a parameter and we use the React setState () method to update the state.

try calling the function like this

this.props.resetPatient(patient, index);

by doing () => this.props.resetPatient(patient, index); you are just declaring another function which you have to call again, you can change it to

(() => this.props.resetPatient(patient, index))();

But that seems rather unnecessary.

Call child method from parent, How do you call a child component function from parent in react? In the parent we'll render the Child component and we'll send as a property (in this case action) the handler function declared in the parent. The Child component in this case is very simple, it will draw a button which action Prop (sent in the parent component) will be triggered when the button is clicked:

How to change the state of a child component from its parent in React, First, we will create a Superhero component with a name attribute in state. This component will render that name first. Now let's create a function  From Parent to Child Using Props. Let us consider our directory structure to be such that the Parent Component renders child components in the Application. App └── Parent ├── Child1 └── Child2. This is the easiest direction of data flow in React and the most basic one.

How to access childs state from parent component in React, The best way to access child state from a parent component is through callback functions, such as onChange or onSubmit. You can also use useRef to get the  This way the child can update the parent's state with the call of a function passed with props. But you will have to rethink your components' structure, because as I understand components 5 and 3 are not related.

How to update parent state from child component in React, You may want to modify some properties in the state of the parent component from a child component. Although there's no directly way as  I have a React app, where props from a parent component are passed to a child component and the props then set the state on the child. After I send an updated value to the parent component, the child component isn't updating the state with the updated props.

Comments
  • Possible duplicate of stackoverflow.com/questions/29100774/…
  • in your component(4), where does index come from? you're not handing it down in your Parent, for instance.
  • thanks for you answer. that helped