Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass state from child to parent component in React Native

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?

like image 689
Forrest Avatar asked Jul 02 '17 22:07

Forrest


2 Answers

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>
    }
}
like image 146
Kishan Mundha Avatar answered Oct 08 '22 21:10

Kishan Mundha


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>
    );
  }
}
like image 20
chapeljuice Avatar answered Oct 08 '22 20:10

chapeljuice