• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

213
Vistas
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 3 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

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 3 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda