theva theva - 1 month ago 21
React JSX Question

react toggle menu, styling the button different on click

I am trying to build a mobile hamburger menu in my react application, following the How to build a sliding menu using React and Less tutorial.

It is all working fine but I would like to toggle the style of the button depending on if the menu is visible or not. Because of that I tried to but the menu button inside the Menu class instead of outside of it, but that gave me errors. The errors says that I cannot modify the state from within the render function. So, how could i solve this?

I am used to not use react, and in that case I would simply have created a class "showing-menu" on the body element, then I could change whatever style I want depending on if the menu is visible or not. This approach seems to be not so Reacive though, how can I solve this in React?


You could hold the the menu toggle in the state then just append that class to the class list. I can't see your existing code so here is what I mean..

class MyClass extends React.Component {
    constructor(props) {
        this.state = {
          toggled: false

        this.handleClick = this.handleClick.bind(this);

    handleClick() {
          toggled: true

    render() {
        return (
            <div className={"specialClass " + this.state.toggled ? 'myToggledClass' : ''}>
            <button onClick={this.handleClick}>Click me!</button>

So in the above example, as soon as the state toggled is set to true, the myToggledClass is appended to the div class list.