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

162
Vistas
cant remove item from array by index

I seem to be passing everything over correctly.

  • When I try removing the item from my array it removes every other item except the one I want to remove. also altars the item. for example, if the item was a string ss.
  • If I remove the last item from the array that is 2 characters for example 77. it would change every item that is 2 character long in the array to 7. And remove every other item
  • If I remove the first item from the array it clears the entire array

what I need to happen

remove the item from the array that matches the var itemIndex


parent comp

const Pagethree = () => {
const[items,setItem] = useState([]);
return(
        <ul>
            {
            items.map((items, i) =>
                <ListItem index={i} item={items} setItem={setItem}/>)
            }
        </ul>
)

child comp

import React, {useState} from "react";

const ListItem = (props) =>{
const {item, setItem, index} = props;

const removeItem = e =>{
    var array = [...item];
    var indexItem = index;
    if (indexItem !== -1){
        array.splice(indexItem, 1);
        setItem(array);
    }
    console.log(array);
}

return(
    <div>
        <ul>
            {
                <div class="flex">
                    {item}
                    <button onClick={removeItem}>delete</button>
                </div>
            }
        </ul>
    </div>
)
};

export default ListItem;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your parent component should be managing the state. All you should be passing down to the child component from the parent is the data that it needs to render, and a handler for the delete button.

const { useState } = React;

// Passing a value, and index, and the handler
function ListItem({ value, index, updateState }) {
  
  // When `handleDelete` is called, call
  // the `updateState` with the item index
  // as an argument
  function handleDelete() {
    updateState(index);
  }
  
  // The button calls the local function when
  // it is clicked
  return (
    <li>
      {value}
      &nbsp;
      <button onClick={handleDelete}>Delete</button>
    </li>
  );
}

function Example({ data }) {

  const [ items, setItems ] = useState(data);

  // `filter` out the items that don't have
  // the deleted item's index, and update state
  function updateState(index) {
   const updated = items.filter((_, i) => i !== index);
   setItems(updated);
  }

  // `map` over the data making sure
  // that `updateState` is passed down in the props
  return (
    <ul>
      {items.map((el, i) => {
        return (
          <ListItem
            key={i}
            value={el}
            index={i}
            updateState={updateState}
          />
        )
      })}
    </ul>
  );
};

const data = [1, 2, 3, 4 ];

ReactDOM.render(
  <Example data={data} />,
  document.getElementById('react')
);
ul { list-style-type: none;  padding: 0; margin: 0; }
li { margin-bottom: 1em; }
<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