Home > Blockchain >  How can I use reactjs state for component class?
How can I use reactjs state for component class?

Time:05-13

I have a sidebar component and the css prepared (.sidebar.active is the class whenever the sidebar is shown) in React:

export default function Sidebar() {
   return (
     <div className="sidebar">This is a sidebar</div>
   )
}

I want to save the state where the sidebar is toggled/active in React and since this is not a class I will have to use the useState hook, right? So it might look something like this:

export default function Sidebar() {
   const [toggled, setToggled] = useState();

   return (
     <div className="sidebar">This is a sidebar</div>
   )
}

How can I dynamically add/remove the .active class? I was thinking of adding additional string, like:

<div className="sidebar {toggled}">This is a sidebar</div>

so toggled is either an empty string or active. What is the correct way? Is there a way where I can dynamically add/remove the class from the classList of the DOM element? Thank you in advance!

CodePudding user response:

You can use the Ternary Operator to toggle the classlist.

export default function Sidebar() {
const [toggled, setToggled] = useState(false);

return (
 <div className={toggled ? "sidebar active" : "sidebar"}>This is a sidebar</div>
)}
  • Related