< Back to Coding, React

Using state to toggle content visibility

Here is the code:

import React from 'react';

class Navigation extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            showNav: false,
        }

        this.toggleMenu = this.toggleMenu.bind(this);
    }

    toggleMenu() {
        this.setState(prevState => ({ showNav: !prevState.showNav }));
    }

    render() {

        return (
            <>
                <button onClick={this.toggleMenu}>menu</button>
                <div className={"nav" + (this.state.showNav ? "" : " hidden") }>
                /* nav links here */
                </div>
            </>
        )
    }
}

export default Navigation;

We set up the default state in the constructor and bind the on click function that toggles the state using the previous state. The bind makes “this” work in the function. Then the navigation’s class updates when the state changes.

Leave a Reply

Your email address will not be published. Required fields are marked *