Skip to content Skip to sidebar Skip to footer

Change Parent's State From A Child And Use It In Another Child React-native

I need to change parent component A's state from a child component B and use that updated state in another child component C of that parent component A . I did the following. I cou

Solution 1:

you need to use componentWillReceiveProps function in C class. Using this method you can update C class according to its updated props.

componentWillReceiveProps(nextProps)
{
   if(this.props.name != nextProps.name)
   {
    //do your task
     this.setState({name:nextProps.name})
   }
}

https://facebook.github.io/react/docs/component-specs.html

Solution 2:

Your component C should not be using the state. State is only useful when the information needs to change from within your component, if all you need is the information passed from the component above simply point to the props.

classCextendsComponent {

  saveData(){
    console.log(this.props.name);   
  }

  render() {
    return (
      <View><TouchableOpacityonPress={() => this.saveData()}> </TouchableOpacity></View>);
  }
}

If you must have the property transferred to a state, then refer to Burak's answer.

Post a Comment for "Change Parent's State From A Child And Use It In Another Child React-native"