Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directly modify parent props from the child in react

In a wizard in step 1, can I directly modify a parent prop, so after mounting step 2, it will have the that prop modified prop available? Or how should I do it?

Wizard component, render

<Wizard>
  {this.state.step1 &&
    <Step1 dataWizard={this.state.dataWizard} />
  }
  {this.state.step2 &&
    <Step2 dataWizard={this.state.dataWizard} />
  }
</Wizard>

Step1 component

class Step1 extends React.Component {

  ...

  updateData() {
    this.props.dataWizard.idCreation = 432876;
  }
like image 278
user2952265 Avatar asked Sep 30 '25 09:09

user2952265


2 Answers

You should use the state, because

Props are Read-Only

You should use a state in the component which renders Wizard, and when Step1 is finished, it alters that state, which then will be used in Step2.

This is called Lifting State Up.

like image 165
ChrisR Avatar answered Oct 02 '25 05:10

ChrisR


props, like state, is read-only and should never be mutated.

You should use a callback:

<Step1 
  dataWizzard={this.state.dataWizzard} 
  updateData={idCreation => 
    this.setState(prevState => ({ 
      dataWizzard: {
        ...prevState.dataWizzard,
        idCreation,
      },
    }))
  } 
/>

Then you call the callback in Step1:

updateData() {
  this.props.updateData(432876);
}
like image 24
Roy Wang Avatar answered Oct 02 '25 05:10

Roy Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!