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

280
Views
JavaScript Array conflicting with React Component

I have three checkboxes that when selected fire a function. I'm using React-Bootstrap and my code is like this:

    let departmentArray = ([]);
    
      function handleCheck(val) {

        //DEPARTMENT ARRAY LOAD
        const index = departmentArray.indexOf(val);
        if (index > -1) {
          departmentArray.splice(index, 1);
        } else {
          departmentArray.push(val);
        }

        //REACT COMPONENT 
        if (val === "Maintenance") {
          setMaintCheck(!maintCheck);
        } else if (val === "Process") {
          setProcCheck(!procCheck);
        } else if (val === "Toolroom") {
          setToolCheck(!toolCheck);
        }

      }; 

  return (
    <>
       <Form.Check name={'department'} onClick={(e) => {handleCheck("Maintenance")}} checked={maintCheck} />
       <Form.Check name={'department'} onClick={(e) => {handleCheck("Process");}} checked={procCheck} />
       <Form.Check name={'department'} onClick={(e) => {handleCheck("Toolroom");}} checked={toolCheck} />
    </>
  )

The state of the checkboxes works with this code, but the array departmentArray does not work if the code underneath //REACT COMPONENT is present. If I remove these lines, the departmentArray loads correctly. I have no idea why the two would be affecting each other.

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

The departmentArray seems to be a normal var for React, when the code that is under // REACT COMPONENT executes the component rerenders and departmentArray reinitializes to []. You can put departmentArray out of the component as a constant or declare it as a state var for the component reacts to its changes

This is what I mean:

const departmentArray = []

const component = (props) => {

   const loadData = () => {
      // get data from somewhere
      departmentArray.push(...)
   }
   return <></>
}

Or you can declare departmentArray as a state var:

const [departmentArray, setDepartmentArray] = useState([])

const loadDepartments = () => {
   // load data
}

useEffect(loadDeparments, [])

about 4 years ago · Santiago Gelvez 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!