Just Ahead
Just Ahead

Reputation: 2487

How to change screen using stackNavigation in React Native?

I have one screen which in header consists button to go to another screen.

I have already model here, but it doesn't work: As shown below I want to change the screen from RecipeList to NewRecipeForm using Button in header

const AppStackNavigator = createStackNavigator({
 List: {
  screen: RecipesList,
  navigationOptions: {
    title:'RecipesList',
    headerLeft: (
      <Button onPress={()=>this.props.navigation.navigate('NewRecipeForm')}>
      <Text>+</Text>
      </Button>
    )
    }},
 NewRecipeForm: {screen: CreateRecipeForm, 
        navigationOptions: {title:'Add new recipe'}},
  Details: {screen: RecipesDetails, navigationOptions: {title:'RecipeDetails'}},

export default class App extends React.Component {
 render() {
  return <AppStackNavigator initialRouteName='List' />;
   }
}

I hope that you will help me with solution

Upvotes: 0

Views: 1406

Answers (3)

Jeeva
Jeeva

Reputation: 1590

You may use your stack navigator as like below, you can able to destructure your navigation property while giving your navigationOptions property as well in the createStackNavigator itself

const AppStackNavigator = createStackNavigator({
    List: {
        screen: RecipesList,
        navigationOptions: ({navigation}) => {  //destructure the navigation property here 
            return {
                title: 'RecipesList',
                headerLeft: (
                    <Button onPress={() => navigation.navigate('NewRecipeForm')}>
                        <Text>+</Text>
                    </Button>
                )
            }
        }
    },
    NewRecipeForm: {
        screen: CreateRecipeForm,
        navigationOptions: { title: 'Add new recipe' }
    },
    Details: { screen: RecipesDetails, navigationOptions: { title: 'RecipeDetails' } }

});

Upvotes: 2

Dinith Minura
Dinith Minura

Reputation: 1496

You can use following code inside your RecipesList Component instead of having it inside createStackNavigator(). See this Snack for full implementation.

static navigationOptions = ({ navigation }) => {
    return {
      headerTitle: "RecipesList",
      headerLeft: (
        <Button
          onPress={() => navigation.navigate('NewRecipeForm')}
          title="+"
        />
      ),
    };
  };

Upvotes: 1

sanjar
sanjar

Reputation: 1101

You cannot access the props of your component in headerLeft, but you can directly use the navigation like this :

  <Button onPress={()=> navigation.navigate('NewRecipeForm')}>

Upvotes: 2

Related Questions