react-nativereact-native-navigationlaw-of-demeter

React native navigation params and demeter law


When you want to access params in a screen component passed through navigation (react native navigation), you have to do it like this for example:

this.myParameter = this.navigation.state.params.myParameter 

Does this break demeter law ? And what if you want to use deep linking later on ?

A solution would be to just create a wrapper component that maps the navigation parameters as props.


Solution

  • Indeed, the Law of Demeter (or Principle of Least Knowledge) would require that your component know nothing about the internal structure of the navigation object.

    In my view, the best thing would have been that the navigation object passed down to the component would have already had a function called params(), which would have returned a parameter map to you.

    However, since this is not the case, you could just add it yourself - either by introducing a layer of indirection (through a function of your own that would look like screenParamsFrom(navigation), or you could try to hook into the navigation object and add the function yourself by supplying the navigation object to the root navigator:

    <MyRootNavigator navigation={addNavigationHelpers({
        dispatch: dispatch, 
        state: state, 
        params: paramsFunction})}/>
    

    In this case, however, you'll have to manage the state yourself (through Redux or some other similar mechanism. See the integration guide).