Search code examples
react-nativereact-navigationreact-navigation-stack

I've got a few questions regarding modals in react-native


I'm new to react-native. So, I've been going through some documentation on react-navigation website to understand how modals etc. work. This code is available here: https://reactnavigation.org/docs/en/modal.html I don't understand a few things:

  1. Why is the following code needed and what is it doing exactly:
    static navigationOptions = ({ navigation }) => {
    const params = navigation.state.params || {};
  1. Why aren't we calling this.props.navigation.navigate instead of just navigation.navigate in this line:
onPress={() => navigation.navigate('MyModal')}
  1. Instead of using a StackNavigator, can I use a drawer navigator and would that work? If yes, how can I use it here?
class HomeScreen extends React.Component {
  static navigationOptions = ({ navigation }) => {
    const params = navigation.state.params || {};

    return {
      headerLeft: (
        <Button
          onPress={() => navigation.navigate('MyModal')}
          title="Info"
          color="#fff"
        />
      ),
      /* the rest of this config is unchanged */
    };
  };

  /* render function, etc */
}

class ModalScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text style={{ fontSize: 30 }}>This is a modal!</Text>
        <Button
          onPress={() => this.props.navigation.goBack()}
          title="Dismiss"
        />
      </View>
    );
  }
}

const MainStack = createStackNavigator(
  {
    Home: {
      screen: HomeScreen,
    },
    Details: {
      screen: DetailsScreen,
    },
  },
  {
    /* Same configuration as before */
  }
);

const RootStack = createStackNavigator(
  {
    Main: {
      screen: MainStack,
    },
    MyModal: {
      screen: ModalScreen,
    },
  },
  {
    mode: 'modal',
    headerMode: 'none',
  }
);

Solution

  • The first question and the second question are the same question. You are passing the navigation object as a parameter in NavigationOption. That is why you do not use 'this.props.navigation' that you received from parents.

    You need to study parameters. This question seems to be asked because of a lack of understanding of parameters.

    useful links

    1. about parameters

    And if you want to use a drawer Navigator, you have to configure it the same way as a stack navigator.

    useful links

    1. about drawer Navigator
    2. drawer Navigator example