Answer the question
In order to leave comments, you need to log in
How to change class on icon click in React js?
New to react. Sawed navbar (navigation menu). When the Icon is clicked, the .sidebar class must be appended with the .active class to make it (sidebar active). CSS styles are already written. Respectively, when you click again, remove it. Only one icon to click on. In js I understand how to implement it. But in React I can’t understand at all how you can quickly change the code without creating arrays and props. In theory, there should be a simple answer, but for the life of me I can not find a solution. Everything is so dreary here (in js you need to write 3-4 lines), but here it’s completely different to write the campaign (it’s wildly annoying, why am I learning js), please help.
a class should be added to it when clicked, so that it turns out and the menu will open and close. <div className="sidebar">
<div className="sidebar active">
Answer the question
In order to leave comments, you need to log in
Look, there are several ways:
1) hang up a click on the div, and change the state, for example const [activeState, setActiveState] = useState(false); Click will change activeState like this setActiveState(prev => !prev); That is, with each click, activeState will be either true or false. Your div will look like this
<div className={`sidebar ${activeState ? 'active' : ''}`}>
It is not necessary to write this inside a div and not necessarily through a ternary, you can put this logic into a separate function that will return classes to you by condition. Just see that each expander must be a separate component so that it has its own state, otherwise all expanders will be expanded at the same time))). Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question