简体   繁体   中英

How to toggle class when click button in React.js

I want to toggle class to button , and nav .

This is what I tried.

import React from 'react';
  
class About extends React.Component{
  render(){ 
    return (
    <>
      <button className={`btn-toggle ${show ? "btn-active" : ""}`}>>
        Toggle
      </button>
      <nav className={`nav-toggle ${show ? "nav-active" : ""}`}>menu</nav>
    </>
    )
  }
}
export default About;

What do I need to do?

You can try somthing like this but Im not sure why are want to toggle button because you always need to have something shown on which you can click and display nav. But as its metioned, it's not good practise to change classes

import React, { useState } from 'react';
  
const About = () => {
   const [navVisible, setNavVisible] = useState(false);
   const [btnVisible, setBtnVisible] = useState(true);

    return (
    <>
      <button onClick={() => setNavVisible(!navVisible)} className={`btn-toggle ${show ? "btn-active" : ""}`}>>
        Toggle
      </button>
      <nav className={`nav-toggle ${navVisible ? "nav-active" : ""}`}>menu</nav>
    </>
    )
}
export default About;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM