Search code examples
javascriptreact-nativetabnavigator

how to pass properties to a react-native component inside a tab navigator?


I have the following code:

import React, { Component } from 'react';
import {TabNavigator} from 'react-navigation';
import {Button,FlatList,Text,View} from 'react-native';

class Recent extends Component<{}> {

  getData() {
      return ["Locked in room","Fell on the floor", "Need help with Stairs"];
  }
  render() {

    let {navigate} = this.props.navigation;


    console.log(this.props.user); // this line gives me undefined
    return (
        <FlatList
          style={{flex:1,width:"100%"}}
          data={this.getData()}
          keyExtractor={(item, index) => index}
          renderItem={({item}) => <Text onPress={()=>navigate("NextPage",{user:this.props.user})}>{item}</Text>}
        />
    );
  }
}

const RequestRouter = TabNavigator({
  Recent1: {screen: Recent},
  Recent2:{screen:Recent}
  }
);

export default class App extends Component<{}> {

  render() {

    let {navigate} = this.props.navigation;
    const user = this.props.navigation.state.params.user;

    return (
        <View style={{flex:1,flexDirection:"column"}}>
            <Button onPress={()=>navigate("NextPage",{user:user})}
                title="Go"
                accessibilityLabel="Go"
            />
            <View style={{width:"100%",flex:6,flexDirection:"column"}}>
            <RequestRouter user={user} />
            </View>
        </View>
    );
  }
}

The issue I'm having is that the console.log(this.props.user); inside the class Recent extends Component gives me an undefined. This is because I don't know how to properly pass the user variable in the App.render() into the Recent.render(), since there is a TabNavigator that routes requests to the Recent class.

How do I pass the user variable from App.render() into Recent?


Solution

  • You can use screenProps to pass props to child component inside TabNavigator like this:

    <RequestRouter screenProps={user} />
    

    You can access it in child component by this.props.screenProps.user