Data transfer between components React-native

1.1k views Asked by At

I have two components I want to pass some property data from on page to other page/component. But unable to do that with props.

<TouchableOpacity onPress={() => {this.navigateTo('component2'); setState(url: 'www.xyz.com', data: 'abc' }>
  <View style={{ flexDirection: 'row', height: 60, justifyContent: 'center', alignItems: 'center', paddingLeft: 10 }}>
    <Image source={deals} />
    <View style={{ flex: 1 }}>
      <Text style={{ color: '#000' }}> Deal Center </Text>
    </View>
  </View>
</TouchableOpacity>

and want to read the state from component2. Can anyone please help

2

There are 2 answers

0
Nguyên Hoàng On

you can write a function which navigator to 1 Component and passProps.

Example :

navigateTo(component){
  this.props.navigator.push({
    name: component,
    passProps: {
      url: 'www.xyz.com',
      data: 'abc' 
    }
  })
}

And place this function in your code like :

<TouchableOpacity onPress={this.navigateTo.bind(this,'component')}>
        ...
</TouchableOpacity>

In your 2nd component, you can call props like :

this.props.url or this.props.data

Here is a good tutorial for React Native Navigator, take a look

1
Shailesh Prajapati On

First of all you have to set routes like.

<Second navigator={navigator} {...route.passProps}  />

then only you can pass the props to the second component

then call your method on click

_navigate(component,data) {
   this.props.navigator.push({
   name: component,
   passProps: {
     data:data
    }
   })
 }

in second component you can access data using this.props.data