Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Navigation: Use/Change header title with Redux state

Is it possible to access the whole Redux state inside the React Navigation's header title?

The official docs says that the state corresponding to the navigation is accessible:

  static navigationOptions = {
    title: ({ state }) => `Chat with ${state.params.user}`
  };

But I wish to access other parts of my Redux state, with the title updating when that state updates. Is that possible today?

like image 369
jeanpaul62 Avatar asked Mar 24 '17 11:03

jeanpaul62


2 Answers

this is possible with a little workaround. I would not even call this a workaround either I would call this a great feature :-)

you just have to use a new component in your header like this:

static navigationOptions = {
    header: (navigation) => {
        return <HomeViewTitle />;
    }
}

and then you can connect in my case HomeViewTitle with the redux state:

import React, { Component } from 'react';

import {
    View,
    Text
} from 'react-native';

import { connect } from 'react-redux';


class HomeViewTitle extends Component {

    render() {

        return (

            <View style={{height: 64, backgroundColor: '#000000', alignItems: 'center', justifyContent: 'center', paddingTop: 20}}>
                <Text style={{color: '#FFFFFF', fontSize: 17, fontWeight: 'bold'}}>Home</Text>
            </View>

        );

    }

}

const mapStateToProps = (state) => {
    return state;
}

export default connect(mapStateToProps)(HomeViewTitle);

then you have your redux state as props in HomeViewTitle and you can set the header dynamic

like image 183
vanBrunneren Avatar answered Nov 06 '22 01:11

vanBrunneren


An easier way to do this that preserves the styles of the header component is to utilize React-Navigation's getParam and setParams. In navigationOptions you would have:

static navigationOptions = ({ navigation }) => {
   return {
      title: navigation.getParam('title', 'DEFAULT VALUE IF PARAM IS NOT DEFINED'),
   };
}

and then in componentWillMount() you would have:

componentWillMount(){
   this.props.navigation.setParams({ 'title': this.props.title })
}

make sure to dispatch the title to props

const mapStateToProps = state => {
  return {
    title: state.titleSavedInState,
  }
};

The above is sufficient if you are not making any changes to the state before the state of the component (note that updating the state in redux only updates the props of the components) is updated again. However, if you are going to do be making changes while the component is open, you also need to use:

componentWillUpdate(nextProps, nextState){
    if(this.props.navigation.getParam('title', 'DEFAULT') != this.props.titleSavedInState)
    this.props.navigation.setParams({ 'title': this.props.titleSavedInState })
}
like image 7
Eric Wiener Avatar answered Nov 06 '22 01:11

Eric Wiener