javascript - How to toggle css class on React - Stack Overflow

Learning React and trying to simply toggle a css class on body tag when a element in my ponent is click

Learning React and trying to simply toggle a css class on body tag when a element in my ponent 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?

Learning React and trying to simply toggle a css class on body tag when a element in my ponent 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?

Share Improve this question edited Apr 29, 2018 at 16:41 user2300867 asked Apr 29, 2018 at 16:38 user2300867user2300867 6031 gold badge14 silver badges28 bronze badges 1
  • You can do it using setState, the right question here is how to toggle class using vanilla JavaScript. – Adam Azad Commented Apr 29, 2018 at 16:40
Add a ment  | 

4 Answers 4

Reset to default 3

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.

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

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744398906a4572286.html

相关推荐

  • javascript - How to toggle css class on React - Stack Overflow

    Learning React and trying to simply toggle a css class on body tag when a element in my ponent is click

    7天前
    60

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信