Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data between react native screens?

Hey I am new to react native. So basically I have a stack navigator with two screen option: Screen 1 (Default) and Screen2. I already set up a button so that when pressed it will take me to Screen 2. So in Screen1 I have an array displayed as scrollview component. Now when i press the button to go to screen2 I want to pass some of the array values to that screen2 component. What is the best way to do it? Thank you :)

I am really new so my attempts are kinda dumb. I tried importing the Screen1 component and calling the array values via this.state but no access.

like image 793
Actssassin Avatar asked Dec 27 '18 09:12

Actssassin


People also ask

How do I pass values from one page to another in react?

You can use the Link component from react-router and specify to={} as an object where you specify pathname as the route to go to. Then add a variable e.g. data to hold the value you want to pass on.

Can we pass data from child to parent in react native?

While there is no direct way to pass data from the child to the parent component, there are workarounds. The most common one is to pass a handler function from the parent to the child component that accepts an argument which is the data from the child component.


2 Answers

The easiest way to pass the data is when you are navigating. To do that it is better that you put your array in a state an then use the following method:

onPress=()=>{
     this.props.navigation.navigate('Screen2', {
          yourArray: this.state.yourArray, });
      }
}

Then in the next screen(Screen2) you can find the array(your data) in the props.So in your constructor in scrren2 you can find the data here:

  constructor(props) {
    super(props);

    var params = props.navigation.state.params.yourArray;

}

Also to come back to your previous screen without touching your states you can use this code in your back button:

  const { goBack } = this.props.navigation;
      goBack();
like image 52
Reza Avatar answered Oct 05 '22 23:10

Reza


To pass data from Screen1 to Screen2. Here we're storing the array in a state.

onPress={() => this.props.navigation.navigate('Screen2', {array: this.state.array})}

To get the data from Screen1 in Screen2

this.props.route.params.array

The source of this response is official documentation. I have tried it as well because the above solution didn't work for me. For more information you can go to this React Navigation Docs.

like image 44
Anand Nigam Avatar answered Oct 06 '22 01:10

Anand Nigam