Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
Array.splice not woking when there is one index left

My idea in the code is to handle and store the change on checkbox in array when I uncheck one of the checkboxs It will splice and remove its index. The problem is it will not remove the last index even when it's checkbox is unchecked and its value is false.

The code:

 CheckBoxHandler1(e) {
    let temp = [...this.state.boxes];
    console.log(e.target.checked);
    e.target.checked === false
      ? temp.splice(e.target.value, 1)
      : (temp[e.target.value] = [e.target.checked, e.target.name]);

    this.setState({ boxes: temp, checked: e.target.checked });
    console.log(temp);
    console.log(this.state.boxes);
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You should probably be storing the state of all the boxes rather than removing them. You can initially start off with an empty object for the array and then update that when each box changes.

const { useEffect, useState } = React;

function Example() {

  const [ boxes, setBoxes ] = useState({});

  // The `handleChange` is on the parent element
  // so we need to extract the nodeName, the name of
  // the checkbox, and it's status, and then if we've
  // actually un/checked a box, update the state.
  function handleChange(e) {
    const { nodeName, checked, name } = e.target;
    if (nodeName === 'INPUT') {
      setBoxes({ ...boxes, [name]: checked });
    }
  }

  // This just confirms the state has been updated
  useEffect(() => console.log(boxes), [boxes]);

  return (
    <div onChange={handleChange}>
      Name: <input name="name" type="checkbox" checked={boxes.name} />
      Age: <input name="age" type="checkbox" checked={boxes.age} />
      Job: <input name="job" type="checkbox" checked={boxes.job} />
    </div>
  );

};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Class component:

const { Component } = React;

class Example extends Component {

  constructor() {
    super();
    this.state = {};
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    const { nodeName, checked, name } = e.target;
    if (nodeName === 'INPUT') {
      this.setState({ ...this.state, [name]: checked }, () => {
        console.log(this.state)
      });
    }
  }

  render() {
    return (
      <div onChange={this.handleChange}>
          Name: <input name="name" type="checkbox" checked={this.state.name} />
          Age: <input name="age" type="checkbox" checked={this.state.age} />
          Job: <input name="job" type="checkbox" checked={this.state.job} />
      </div>
    );
  }

};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza 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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda