I am unfortunately a bit on the tube.
I have three buttons, to filter an array. By default the "All" Button should be active (with a red text-color). If you click on another button, the text-color of the clicked on should become red and the text-color of the others should become/stay grey. That’s my goal. But I can’t wrap my head around it! Hope somebody of you can help me out!
I tried it with this code. But all is does, it turn all buttons blue. How can I modify the code that only the clicked button becomes red text-colored?
export default function App() {
const buttons = document.querySelectorAll(".btn");
buttons.forEach((button, i) => {
button.addEventListener("click", (e) => {
if (parseInt(e.target.value) === i) {
button.style.color = "red";
}
button.style.color = "blue";
});
});
return (
<>
<button className="btn" value={0} style={{ color: "red" }}>
Filter 1
</button>
<button className="btn" value={1}>
Filter 2
</button>
<button className="btn" value={2}>
Filter 3
</button>
</>
);
}
2
Answers
First of all, you should use the state management by React instead of trying to modify the DOM elements directly. If you use state in React, you can easily achieve that by assigning a custom state and an ID for each of your button, like so:
In React, the
App()
function is therender
function, it will be called everytime there’s any state changes (In this case every timesetSelectedBtn
is called), thus it will re-render all the buttons and have their color updated correctly.You can learn more about how it works in React’s documentation. Try to modify the sample code in the page to get a sense of how React works
If you’re starting out with React AngVC’s answer is the best and quickest to understand – it covers state, and how to update that state when a click event is fired.
I’m including this answer too as it deals with
Maintain buttons as configuration (an array of objects) which is sometimes easier to manage at scale
Using a separate (dumb) component for the button, and passing down props where necessary.
Managing state in the parent component.