Rhys
Rhys

Reputation: 51

In React Native how do you change navigation options on state change?

I have a design where the navigation header style color should change depending on the state.

It is possible to change the style the first time the component is mounted. However I can't see a way of changing it on a subsequent state change.

const mapStateToProps = state => {
    return {
        stuff: state.stuff,
    }
}

const mapDispatchToProps = dispatch => ({
    // stuff
})

class Test extends React.Component {

    static navigationOptions = ({ navigation }) => {

       // need to set barcolor to this.props.state.stuff.headerColor
        return { 
            ...
            headerStyle: {
                backgroundColor: ???,
            }  
            ...       
        }
    }


    componentDidMount() {
        // could do it here, but only works on mount
        // this.props.navigation.setParams({ headerColor: this.props.state.stuff.headerColor });
        // then access params from navigation state in navigationOptions
    }


    render() {
        //
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Test);

Is this possible in React Native?

Upvotes: 1

Views: 1263

Answers (1)

Rory Fielding
Rory Fielding

Reputation: 110

Do it in the 'componentDidUpdate()' lifecycle method. On a given condition, you can set the navigation params and also set a boolean value to stop the component entering an infinite loop.


class Test ...

constructor(props){
    super(props)
    this.state = {
    inputSet: false
}

componentDidUpdate(){
    if(condition && !inputSet){
    this.props.navigation.setParams({ headerColor: this.props.state.stuff.headerColor });
    this.setState({inputSet: true});
}

Upvotes: 1

Related Questions