Using state to toggle content visibility

Posted on

in

,

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 *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

June 2024
M T W T F S S
 12
3456789
10111213141516
17181920212223
24252627282930