Toggle Class in React

The Solution to Toggle Class in React is

You have to use the component's State to update component parameters such as Class Name if you want React to render your DOM correctly and efficiently.

UPDATE: I updated the example to toggle the Sidemenu on a button click. This is not necessary, but you can see how it would work. You might need to use "this.state" vs. "this.props" as I have shown. I'm used to working with Redux components.


  return {"showHideSidenav":"hidden"};

render() {
    return (
        <div className="header">
            <i className="border hide-on-small-and-down"></i>
            <div className="container">
                <a ref="btn" onClick={this.toggleSidenav.bind(this)} href="#" className="btn-menu show-on-small"><i></i></a>
                <Menu className="menu hide-on-small-and-down"/>
                <Sidenav className={this.props.showHideSidenav}/>

toggleSidenav() {
    var css = (this.props.showHideSidenav === "hidden") ? "show" : "hidden";

Now, when you toggle the state, the component will update and change the class name of the sidenav component. You can use CSS to show/hide the sidenav using the class names.

.hidden {

~ Answered on 2016-04-04 13:28:14

Most Viewed Questions: