I have Main Component file and use in another child ponent. I have to get state of the child ponent.
Ex :- Home (Parent) - Form (Child) ponent i have been set the value of any text box in state. So ho can i get the state value of Form ponent into the main ponent.
I have Main Component file and use in another child ponent. I have to get state of the child ponent.
Ex :- Home (Parent) - Form (Child) ponent i have been set the value of any text box in state. So ho can i get the state value of Form ponent into the main ponent.
Share Improve this question asked May 11, 2018 at 11:28 Asif voraAsif vora 3,3473 gold badges18 silver badges35 bronze badges 2- You can use state lifting – RIYAJ KHAN Commented May 11, 2018 at 11:30
- Please show us your code. In React data should always flow down in the ponent tree. So instead of passing state up to the parent you should move your state to the parent and pass the data down to the child as props. Also see Lifting State Up in the react docs. – trixn Commented May 11, 2018 at 11:35
3 Answers
Reset to default 5Generally in React (and React-Native) information is passed down from the parent ponent to its children. However if you need to change something in the parent ponent's state based on the child-ponent's state, you can pass a function to the child that does just that.
For example:
// Inside Parent Component
openModalFromParent() {
this.setState({ modalOpened: true });
};
// Passing Function to Child
<ChildComponent openModal={ this.openModalFromParent } />
// Inside Child Component
<TouchableHighlight onPress={ () => this.props.openModal() } />
In this example the button in the child ponent would trigger a function that alters the state of the parent ponent - hope this helps!
Pass the function as a prop to the child ponent
//Parent Component
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
};
this._handleChange = this._handleChange.bind(this);
}
_handleChange(e) {
const { name, value } = e.target;
this.setState({
[name]: value
});
}
render(){
return(){
<Form valueChange={this._handleChange} />
}
}
}
//Child Component
export default class Form extends Component {
render(){
return(){
<div>
<input type="email" name="username" onChange={(e) => this.props.valueChange()} value={username}/>
<input type="password" name="password" onChange={(e) => this.props.valueChange()} value={password}/>
</div>
}
}
}
In React, your state can only flow down from the parent to the children. What you should do is move the state from the child to the parent and then pass the state to the child as props.
Try reading this: https://reactjs/docs/lifting-state-up.html