Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
Cleanup a function with parameters inside a loop of event listener (reactjs)

I don't really know what is going on, but I think that the removeEventListener is not working properly. Here is my code, my app is crashing everytime I click more than 5 times on any of the buttons and I can't find a solution anywhere.

const doTri = (e) => {
    if(e.id === "active"){
      setOrder(!order);
    }
    else {
      document.getElementById("active")?.removeAttribute("id");
      e.setAttribute('id', 'active');
      setTri(e.classList[1]);
      setOrder(true)
    }
  }

useEffect(() => {
    Array.from(document.getElementsByClassName("headerBtn")).forEach((e)=>{
      e.addEventListener('click', ()=>{doTri(e)})
    })
  
    return () => {
      Array.from(document.getElementsByClassName("headerBtn")).forEach((e)=>{
        e.removeEventListener('click',()=>{doTri(e)})
      })
    }
  }, [tri,order])
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

as I said the removeEventListener function wasn't working so I did some changes in order to not pass any params to the do tri functions, that is what I did and it worked.

const doTri = (e) => {
    if(e.currentTarget.id === "active"){
      setOrder(!order);
    }
    else {
      document.getElementById("active")?.removeAttribute("id");
      e.currentTarget.setAttribute('id', 'active');
      setTri(e.currentTarget.classList[1]);
      setOrder(true)
    }
  }

useEffect(() => {
    Array.from(document.getElementsByClassName("headerBtn")).forEach((e)=>{
      e.addEventListener('click', doTri)
    })
  
    return () => {
      Array.from(document.getElementsByClassName("headerBtn")).forEach((e)=>{
        e.removeEventListener('click', doTri)
      })
    }
  }, [tri,order])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!