var buttons = document.getElementsByClassName("time-button");
var click_listener = function(event) {
//console.log("clicked " + event.target);
for (var i = 0; i < buttons.length; i++) {
buttons[i].classList.remove("clicked");
}
event.target.classList.add("clicked");
};
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", click_listener, false);
}
.clicked {
background-color: orange;
}
<button className="time-button">9:30 am</button>
<button className="time-button">9:00 am</button>
<button className="time-button">8:30 am</button>
<button className="time-button">8:00 am</button>
I try to change the background color when click action ! So first click orange , other click without background, . Each button have to be single click to change background!
but I can`t remove class in this way
I expect the code to work with button clicks, first click on orange background, second click without background and so on. The way I did it, I can change one and delete the background of the other buttons, I want each button to work with its click, can someone help ?
In React, you should use state to define how your UI renders, not DOM methods (getElementsByClassName()
, .classList.add()
, etc.). The idea is, if you want to change your UI, you can change your state, which then rerenders your UI accordingly. To achieve what you’re trying to do, you should first start with defining your buttons as objects in an array which you can then .map()
over in your JSX. When you click on a button, you can use the object’s id to mark the currently “active” button (stored in state), which you can use to determine if your clicked
class gets applied to the mapped button:
const { useState } = React;
const times = [
{id: 0, time: "9:30 am"},
{id: 1, time: "9:00 am"},
{id: 2, time: "8:30 am"},
{id: 3, time: "8:00 am"}
];
const App = () => {
const [activeButton, setActiveButton] = useState(-1); // -1 to indicate that there are no active buttons
const handleClick = (id) => {
setActiveButton(currId => currId === id ? -1 : id);
}
return <React.Fragment>
{
times.map(({id, time}) =>
<button
key={id}
className={"time-button" + (id === activeButton ? " clicked" : "")}
onClick={() => handleClick(id)}
>{time}</button>)
}
</React.Fragment>;
}
ReactDOM.createRoot(document.body).render(<App />);
.clicked {
background-color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>