kirimi
kirimi

Reputation: 1400

react-native : How to pass state to nested stackNavigator to tabNavigator

I am trying to use pass state from nested stackNavigator to tabNavigator.

First of all My App.js navigation structure looks like this

App.js

//tabNavigator. This is where I want to pass my state. 
const tabNavigator = createMaterialTopTabNavigator({
    tabOne:tabOne,
    tabTwo: tabTwo,
    tabThree:tabThree
  })

//I nested tabNavigator to this StackNavigator
 const StackNavigator = createStackNavigator({
  stackAndTab: {
    screen: tabNavigator,
    navigationOptions: ({ navigation }) => ({
      header:
      <CustomHeader
        navigation={navigation}
        />
      ,
    })
  },
}, {
  defaultNavigationOptions: {
    header: null
  }
})

//I have another stackNavigator where I put all my stackNavigators.
const AllStackNavigator = createStackNavigator(
  {
    InitialScreen:InitialScreen,
    StackNavigator:StackNavigator,
  },
  {
    defaultNavigationOptions: {
      header: null,
    },
  },
);

//Finally I nest my StackNavigator to SwitchNavigator
const SwitchNavigator = createSwitchNavigator(
  {
  AllStackNavigator:AllStackNavigator
  },
  {
    defaultNavigationOptions: {
      header:  null,
    },
  },
);

const CombinedNavigator = createAppContainer(StartSwitchNavigator);

export default class App extends React.Component {

  render() {
    return <CombinedNavigator/>;
  }
}

I am trying to pass state to the StackNavigator from the InitialScreen like this:

export default class InitialScreen extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      newState:'this is new State'
   }
  }

  render() {

return (
  <View style={styles.container}>
   <TouchableOpacity
  onPress={()=> this.props.navigation.navigate('StackNavigator', {state:'this.state.newState})}
  style={{width:'100%', height:110}}>
  <Text>pass state</Text>
  </TouchableOpacity>
  </View>
   );
  }
}

My Question

How can I access the passed state newState(the state that I passed from initialScreen) in the tabNavigator where tabOne, tabTwo, tabThree is nested.

Upvotes: 0

Views: 420

Answers (1)

shammi
shammi

Reputation: 1419

I saw your problem and I feels your code is little bit in a chaos. you can use this line for getting params which you are pass to StackNavigator. try this code in your Tab Screens this.props.navigation.dangerouslyGetParent().getParam('state')

and please correct your onPress event onPress={()=> this.props.navigation.navigate('StackNavigator', {state:this.state.newState})}

Upvotes: 3

Related Questions