Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

168
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda