user2300867
user2300867

Reputation: 603

How to toggle css class on React

Learning React and trying to simply toggle a css class on body tag when a element in my component is clicked. I can't seem to find a good example on how to do it.

Here is how I would do it using Jquery.

function initNav() {
$(".hmbWrapper").click(function() {
    $('body').toggleClass('mobileNavActive');
});
}

What is the correct approach in React?

Upvotes: 1

Views: 5267

Answers (4)

Sahar Ebrahimi
Sahar Ebrahimi

Reputation: 115

const myComponent = () => {
    [state, setState] = useState('red');
    const colorHandler = () => {
        setState(state === 'red' ? 'blue' : 'red');
    }
    return (<button onClick={colorHandler}>toggle</button>);
}

Upvotes: 0

Evgeniy Volk
Evgeniy Volk

Reputation: 656

class App extends Component {
 toggleClass = (event) => {
   event.target.classList.toggle('selected')
}

render() {
 return (
  <div>
    <button onClick={this.toggleClass}>toggle</button>
  </div>
);
}}

Upvotes: 3

Colin Ricardo
Colin Ricardo

Reputation: 17249

You can do something like this, assuming you have a <div id="test">something</div> in the index.html file.

class App extends Component {
  toggleClass = () => {
    const oldClassName = document.getElementById('test').className;
    const newClassName = oldClassName === 'red' ? 'blue' : 'red'
    document.getElementById('test').className = newClassName
  }

  render() {
    return (
      <div>
        <p>
          click toggle to change colors below
        </p>
        <button onClick={this.toggleClass}>toggle</button>
      </div>
    );
  }
}

Working example here.

Upvotes: 3

Olivier Boiss&#233;
Olivier Boiss&#233;

Reputation: 18113

if the toggled element is not part of React, you can do it in old fashion way using pure javascript.

class MyComponent extends React.Component {
  toggle = () => document.body.classList.toggle('mobileNavActive');

  render() {
    return <button onClick={this.toggle}>toggle</button>;
  }
}

Upvotes: 1

Related Questions