J
J
Jagger54352021-08-11 20:30:15
React
Jagger5435, 2021-08-11 20:30:15

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

1 answer(s)
M
Mad Coder, 2021-08-11
@Jagger5435

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))).
2) event.target and event.currentTarget have not been canceled in React. You can, through a click and event.currentTarget , get the element you clicked on and add a class with vanilla js.
3) use ref to access the home https://reactjs.org/docs/refs-and-the-dom.html and also add the class via regular js methods

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question