Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass state back to parent in React?

I have a form that has a submit button. That form calls a function onclick that sets the state of something from false to true. I then want to pass this state back to the parent so that if it is true it renders componentA but if it is false it renders componentB.

How would I do that in react? I know I need to use state or props but not sure how to do it. also is this contradicting the one-way flow react principle??

ComponentA code:

<form onSubmit={this.handleClick}>   handleClick(event) {     this.setState({ decisionPage: true });     event.preventDefault();   }; 

Parent component that controls what it displays:

return (       <div>       {this.props.decisionPage ?         <div>           <LoginPage />         </div>         :         <div>           <Decision showThanks={this.props.showThanks}/>         </div>       }       </div>     ) 
like image 637
The worm Avatar asked Nov 21 '16 14:11

The worm


People also ask

Can you pass state in react?

In React, sharing state is accomplished by moving it up to the closest common ancestor of the components that need it. This is called “lifting state up”. We will remove the local state from the TemperatureInput and move it into the Calculator instead.

Can we pass props from child to parent react?

Reactjs allows one-way data binding, meaning passing data down the hierarchy from parent to child. To pass data from a child component to its parent, we can call a parent function from the child component with arguments.

Can callback be used to pass data from child to parent?

In the parent component, create a callback function. This callback function will retrieve the data from the child component. Pass the callback function to the child as a props from the parent component. The child component calls the parent callback function using props and passes the data to the parent component.


1 Answers

Move handleClick to the parent and pass it to the child component as a prop.

<LoginPage handleClick={this.handleClick.bind(this)}/> 

Now in the child component:

<form onSubmit={this.props.handleClick}> 

This way submitting the form will update the state in parent component directly. This assumes you don't need to access updated state value in child component. If you do, then you can pass the state value back from the parent to the child as a prop. One-way data flow is maintained.

<LoginPage  handleClick={this.handleClick.bind(this)} decisionPage={this.state.decisionPage}/> 
like image 56
Rami Enbashi Avatar answered Sep 21 '22 03:09

Rami Enbashi