Salman
Salman

Reputation: 1034

How to get object ID onPress and pass that value on to a new screen in React Native?

I've build an React Native app which shows a list of different objects on the ListScreen. I now want to with onPress show one object values on the ViewScreen

I've build my app using React-Redux and React-navigation now I'm not sure if I should store the data of the object in the store, but I'm not sure if that's the right way to use the Redux store (because I currently use it for the cart items) or If there is another way to pass on these value's on to the ViewScreen.

This is a simplification of my app:

I've made a static Data.js file to test app

Data.JS

`id: 0, 
 name: 'John Doe', 
 age: '15',
 gender: 'male',
`

Then I import the data into the ListScreen

List.js

`import { object} from './Data';
 state = {
    object, 
  };
renderRow = (rowData) => { 
    return (
        <View>
            <TouchableOpacity onPress={() => this.props.id.navigation.navigate('ViewScreen')}> 
                <View>
                <Text>
                {rowData.item.name}
                </Text>
            </View>
        </TouchableOpacity>
        </View>
    )
  }
  render() {
    return (    
        <View>
             <FlatList
             renderItem={this.renderRow}
             keyExtractor={(item, index) => index.toString()}
         />
        </View>
    )
  }
`

ViewScreen

` state = {
    object, 
  };
renderRow = (rowData) => { 
    return (
        <View>
            <TouchableOpacity onPress={() => this.props.id.navigation.navigate('ViewScreen')}> 
                <View>
                <Text>
                {rowData.item.name}
                                {rowData.item.age}
                                {rowData.item.gender}
                </Text>
            </View>
        </TouchableOpacity>
        </View>
    )
  }
  render() {
    return (    
        <View>
             <FlatList
             renderItem={this.renderRow}
             keyExtractor={(item, index) => index.toString()}
         />
        </View>
    )
  }
`

How do I pick it up from here? So that the value's get shown in the ViewScreen

Upvotes: 0

Views: 3275

Answers (1)

ArkaneKhan
ArkaneKhan

Reputation: 476

you are almost there just add this second argument to your on press method and it's done.

You will get this data in data prop of next screen.

renderRow = (rowData) => { 
    return (
        <View>
            <TouchableOpacity onPress={() => 
            this.props.id.navigation.navigate('ViewScreen',{data : rowData})}> 
                <View>
                <Text>
                  {rowData.item.name}
                  {rowData.item.age}
                  {rowData.item.gender}
                </Text>
            </View>
        </TouchableOpacity>
        </View>
    )
  }

Upvotes: 1

Related Questions