Pass state from child to parent component in React Native

12,047

Solution 1

You can try redux, It store data in state by props whenever you change data in redux store.

Other idea is, pass a setState method to child component.

Parent

class Parent extends Component {
    updateState (data) {
        this.setState(data);
    }
    render() {
        <View>
            <Child updateParentState={this.updateState.bind(this)} />
        </View>
    }
}

Child

class Child extends Component {
    updateParentState(data) {
        this.props.updateParentState(data);
    }

    render() {
        <View>
            <Button title="Change" onPress={() => {this.updateParentState({name: 'test'})}} />
        </View>
    }
}

Solution 2

You should look into a state management module such as Redux to see if it would work with your app, but without anything you can achieve it by doing something like this:

// ---------------------------------------------
// Parent:

class Parent extends React.Component {
  updateData = (data) => {
    console.log(`This data isn't parent data. It's ${data}.`)
    // data should be 'child data' when the
    // Test button in the child component is clicked
  }
  render() {
    return (
      <Child updateData={val => this.updateData(val)} />
    );
  }
}

// ---------------------------------------------
// Child:

class Child extends React.Component {
  const passedData = 'child data'
  handleClick = () => {
    this.props.updateData(passedData);
  }
  render() {
    return (
      <button onClick={this.handleClick()}>Test</button>
    );
  }
}

Solution 3

After trying several different options, we decided to implement Redux to manage state in our app. This was difficult to do with our navigation, but now that everything is set up I'd say it was well worth the effort. There are other state management solutions like MobX we looked into, but decided to go with Redux because it fit with our navigation layout.

Share:
12,047
Forrest
Author by

Forrest

Updated on June 28, 2022

Comments

  • Forrest
    Forrest almost 2 years

    My app has a settings screen (child component) where you can change information about yourself and I'm trying to get that to render on my app's profile screen (parent component). So the profile screen displays your info and if you want to change any info you do it in settings. Right now any changes I make in the settings screen show up in Firebase but if I go back to the profile screen the changes in settings don't render. Of course if I close the app and reload it the changes will be there because the changes in settings are registering to firebase; however, the state is not passing up from the child component to the parent. Does anyone have any advice on how to pass state from the settings (child) component up to the profile (parent) component?