I'm trying to add Active Class in React using JS dom, but it doesn't work for me Please help in finding the solution. Please give a complete solution that includes the code with a little explanation because I feel that I am confused in dealing with the Dom
<FilterOrder>
<div className="" onClick={ActiveClass}> Today </div>
<div className="" onClick={ActiveClass}> Yesterday </div>
<div className="" onClick={ActiveClass}> This Week </div>
My Function =>
const ActiveClass=(e)=>{
const active=e.target.classList;
const prevActive=document.getElementsByClassName("Active");
prevActive.forEach((e)=>console.log("hello"));
active.classList.add("Active");
}
error =>
DOM mutation is very anti-pattern in React. Use React refs to get access to underlying DOMNodes, or just toggle the classnames the React way using some local state.
This said, the error is caused by getElementsByClassName returning some collection that isn't an actual Array, it returns a HTMLCollection, which is an array-like structure.
There is no forEach method to invoke. You can use Array.from if you want/need to iterate the returned elements.
const ActiveClass = (e) => {
const active = e.target.classList;
const prevActive = document.getElementsByClassName("Active");
Array.from(prevActive).forEach((e) => console.log("hello"));
active.classList.add("Active");
}