Amadou Tafsir Diallo
Amadou Tafsir Diallo

Reputation: 47

How to pass child state to the parent in react-native?

I have child component that have state 'imageLink' set in function that I want to use in parent component. but I always get null even if I set it with setState.

task.then(() => {
    taskSnapshot.ref.getDownloadURL().then(downloadURL => {
      const image = {uri: downloadURL};
      this.setState({imageLink: image});
    });
  });

in parent component

db.collection('childs')
    .add({
      name: this.state.name,
      firstname: this.state.firstname,
      birthDate: this.state.chosenDate,
      gender: this.state.gender,
      birthLocation: this.state.birthLocation,
      rang: this.state.rang,
      imageLink: this.state.imageLink,
    });

Upvotes: 0

Views: 308

Answers (2)

SalemC
SalemC

Reputation: 38

React components don't share state/the setState method like that.

What you want is to lift the child component's state.

Instead of having a state the contains "imageLink" in your child component, add it to the parent component's state (it looks like you've already done that), then pass a method to set that value to the child component via props:

class Child extends React.Component {
    // Here's your method
    someMethod = () => {
        // Now we can use the "setImageLink" prop to set the parent component's "imageLink" state value.
        const { setImageLink } = this.props;

        task.then(() => {
            taskSnapshot.ref.getDownloadURL().then(downloadURL => {
                const image = { uri: downloadURL };

                setImageLink(image);
            });
        });
    }

    render () {
        return null;
    }
}

class Parent extends React.Component {
    state = {
        imageLink: "",
        // ... rest of your state
    }

    setImageLink = (imageLink) => {
        this.setState({ imageLink });
    }

    render () {
        const { imageLink } = this.state;       

        return (
            <Child setImageLink={this.setImageLink} />
        );
    }
}

Upvotes: 1

Ravi Kumar Karunanithi
Ravi Kumar Karunanithi

Reputation: 2218

const ParentComponent = (props) => {
  return(
    <ChildComponent imageLink={(imageLink)=> this.setState({imageLink: imageLink})}/>
  )
}

const ChildComponent = (props) => {
  const sendLinkToParent =(link) => {
    props.imageLink(link);
  }

  return(
    // your code
  )
}

You can call sendLinkToParent to pass your link to parent component.

Upvotes: 0

Related Questions