Search code examples
react-nativereact-native-navigation-v2

React this.props.navigation.openDrawer() in child component?


I have an openDrawer method via React Navigation 2 working great in my View. However, when I create a child component and place my openDrawer button in it, I can no longer access this.props.navigation. How do I pass that down into the child component? I looked at state but that doesn't seem to be the correct way to address this? I am new to React/Native. Here is my button inside the main view and it works fine this way.

<View style={styles.menuBar}> 
<TouchableOpacity style={styles.menuButton} 
 onPress={() => this.props.navigation.openDrawer()}>
<Text>&#9776;</Text>
</TouchableOpacity>
// Other Stuff inside menuBar.
</View>

This menu button has a few other items as well and I am wanting to group together in a class component as a child that I can just import into various screens.

import { topMenuBar } from '../components/menuBar';
<topMenuBar />

However, the menu button no longer works now. I know it's because this.props is now referring to class topMenuBar and not the original class which is part of the nav structure. But I don't know the proper procedure for this step, whether it's using state or calling NavigationActions from react-navigation in the child method somehow.

Thanks for the help!


Solution

  • Every component opened using react-navigation has "this.props.navigation".

    If you need it in child components you should pass to them as a prop:

    export default class Home extends Component{
        render(){
            <View>
                <OtherComponent navigation = {this.props.navigation}/>
            </View>
        }
    }
    

    Note: if you want a better help you should always provide code creating a fiddle and organize better your answers..