I'm working on accordion in reactjs. when I visit site first time or when I refresh. my accordion doesn't work at all. but while in development when I make any changes to useEffect that re-render it. it starts working fine. for example while in development if I open site on localhost and while it is already opened if I add a comment into useEffect it starts working
useEffect(() => {
const accordins = document.querySelectorAll('.accordings .item');
console.log("asdf");
for (let i=0;i<accordins.length;i++) {
accordins[i].addEventListener('click',function(){
let allactive = document.querySelectorAll('.accordings .item.active');
for(let j=0;j<allactive.length;j++){
if(allactive[j] !== accordins[i]) {
allactive[j].classList.remove('active');
}
}
this.classList.toggle("active");
})
}
}, [])
Please read the documentation of the effect hook: https://reactjs.org/docs/hooks-effect.html
The hook (with [] condition) is only executed like componentDidMount which is not equivalent to component did render. This means that it is likely that the entities you are searching for are not yet rendered.
I recommend to take a look at useLayoutEffect (https://reactjs.org/docs/hooks-reference.html#uselayouteffect) which is fired after all DOM mutations.