Search code examples
classroutesheadernavigationreact-navigation

Use 'navigation' and 'route' inside header present in class - React-navigation v5


I'm stuck as I want to switch to the V5 version of react-navigation. With v4, I used to pass my params and use them with :

  • Set :

this.props.navigation.navigate('MyDestination', {myParam: 'value'})

  • Get :

this.props.navigation.getParam('myParam')

With v5, some things changed and I now can't use the this.props.navigation since it's not seemed to be known by the app.

My code is splitted so I have my App.js that only refer to the Navigation class :

import React from 'react';
import { StyleSheet, Text, View } from 'react-native'
import Navigation from './navigation/Navigation'

export default function App() {
  return (
      <Navigation/>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Then my Navigation file contains all the navigation mechanism (I did not added my TabBar yet, since I want to fix the base navigation first) :

import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
import { createBottomTabNavigator } from 'react-navigation-tabs'
import { StyleSheet, Image } from 'react-native'
import React from 'react'
import Home from '../components/Home'
import LendList from '../components/LendList'
import AddMoney from '../components/AddMoney'
import AddStuff from '../components/AddStuff'
import Settings from '../components/Settings'
import Test from '../components/Test'

function HomeScreen() {
    return(
        <Home/>
    )
}

function LendListScreen() {
    return(
        <LendList/>
    )
}

const Stack = createStackNavigator()

function App() {
    return(
        <NavigationContainer>
            <Stack.Navigator initialRouteName="Home">
                <Stack.Screen name="Home"
                component={Home} 
                options={{ title: "Home Page"}}
                />
                <Stack.Screen name="LendList" 
                component={LendList}
                options={{ title: 'Liste' }}
                />
                <Stack.Screen name="AddMoney"
                component={AddMoney} 
                options={{ title: "Ajout Money"}}
                />
                <Stack.Screen name="AddStuff"
                component={AddStuff} 
                options={{ title: "Ajout Stuff"}}
                />
                <Stack.Screen name="Settings"
                component={Settings} 
                options={{ title: "Settings"}}
                />
                <Stack.Screen name="Test"
                component={Test} 
                options={{ title: "Test"}}
                />
            </Stack.Navigator>
        </NavigationContainer>
    )
}

export default App

And then come each of my pages (coded with classes), and here is one example, Home.js (I removed all the Style part to shorten the code displayed here) :

import React from 'react'
import { StyleSheet, Text, Image, View, Button, TouchableOpacity } from 'react-native'
import Moment from 'react-moment'
import { CommonActions } from '@react-navigation/native'
import { useNavigation } from '@react-navigation/native'

class Home extends React.Component {

    static navigationOptions = () => {

        return {
            headerRight: () => <TouchableOpacity style={styles.settings_touchable_headerrightbutton}
                            onPress={() => this.goToSettings()}>
                            <Image style={styles.settings_image}
                            source={require('../assets/ic_settings.png')} />
            </TouchableOpacity>
        }
    }

    constructor(props) {
        super(props)
        this._goToSettings = this._goToSettings.bind(this)
    }

    _updateNavigationParams() {
        navigation.setParams({
          goToSettings: this._goToSettings
        })
    }

    componentDidMount(){
        console.log("navigation")
        this._updateNavigationParams()

    }

    _checkMoneyDetails(navigation){
        navigation.navigate('LendList', {type: 'Money'})
    }

    _checkStuffDetails(navigation){
        navigation.navigate('LendList', {type: 'Stuff'})
    }

    _checkPeopleDetails(navigation){
        navigation.navigate('LendList', {type: 'People'})
    }

    _goToSettings = () => {
        navigation.navigate('Settings')
    }

    render(){
        const date = new Date();
        const { navigation } = this.props;

        return(
            <View style={styles.main_container}>
                <View style={styles.header_view}>
                    <Text style={styles.header_text}>GiViToMe</Text>
                    <Text style={styles.header_text}>Nous sommes le :{' '}
                    {/* TODO: Penser à gérer ensuite les formats de date étrangers */}
                        <Moment element={Text} format="DD/MM/YYYY" date={date}/>
                    </Text>
                </View>
                <View style={styles.lend_view}>
                    <Text style={styles.title_lend_text}>Vos prêts :</Text>
                    <View style={styles.money_stuff_view}>
                        <View style={styles.money_view}>
                            <View style={styles.money_data_view}>
                                <Image source={require('../assets/ic_money.png')} style={styles.home_img} />
                                <Text>XXX $</Text>
                            </View>
                            <Button title='Money' onPress={() => {this._checkMoneyDetails(navigation)}}/>
                        </View>
                        <View style={styles.stuff_view}>
                            <View style={styles.stuff_data_view}>
                                <Image source={require('../assets/ic_box.png')} style={styles.home_img} />
                                <Text>XXX objets</Text>
                            </View>
                            <Button title='Stuff' onPress={() => {this._checkStuffDetails(navigation)}}/>
                        </View>
                    </View>
                    <View style={styles.people_view}>
                        <View style={styles.people_data_view}>
                            <Image source={require('../assets/ic_people.png')} style={styles.home_img} />
                            <Text>XXX people</Text>
                        </View>
                        <Button title='People' onPress={() => {this._checkPeopleDetails(navigation)}}/>
                    </View>
                </View>
                <View style={styles.footer_view}>
                    <Text style={styles.text_footer_view}>a.vescera inc.</Text>
                </View>
            </View>
        )
    }    
}

export default Home

My problem is that, per the online documentation, I saw that to use "navigation" or "route" within a class, I should use the const navigation = { this.props } after the render() function.

This problem is that, to use one specific function within the header, I have to bind it after the componentDidMount() function, but the value present under render() is not yet known.

How could I solve this ? (sure that in the given example, having all the code in the navigation part allow to use navigation and route easily but you understand that I have to split my code.

Thanks.


Solution

  • Ok, so each time the same, I try many days solving my problem, and when I finally decide to post on stack, I find a solution :).

    So, if there's some performance issue or other you may see by looking at my code, do not hesitate to correct me. I just found that this solution solved my problem.

    So within my Navigation.js file, I just passed the navigation and route objects to make them usable thanks to the props into my classes, like this :

    function App() {
        return(
            <NavigationContainer>
                <Stack.Navigator initialRouteName="Home">
                    <Stack.Screen name="Home"
                    component={Home} 
                    options={({route, navigation}) => (
                        {headerTitle: 'Home Page', 
                        route: {route}, 
                        navigation: {navigation}}
                    )}
                    />
                </Stack.Navigator>
            </NavigatorContainer>
    )}
    

    then within my classes I just call to this.props.navigation or this.props.route and gather form these objects what I need.

    Other thing is that, for those who would use this code to build something similar, I also had to change the way I display the header button. I do not use the static navigationOptions = () => {} anymore. I just add directly the navigation.setOptions piece of code within the ComponentDidMount function like this:

    navigation.setOptions({
                headerRight: () => <TouchableOpacity style={styles.settings_touchable_headerrightbutton}
                                onPress={() => route.params.goToSettings()}>
                                <Image style={styles.settings_image}
                                source={require('../assets/ic_settings.png')} />
                </TouchableOpacity>
            })
    

    I have to do it this way since I'm using a function declared in my class, so I have to bind it in the constructor like this this._goToSettings = this._goToSettings.bind(this) and then add it to the navigation.setParams function.