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

243
Visualizações
How to delete item on click in React

I am trying to delete an item in React by clicking on a button. Currently my code returns Cannot read properties of undefined (reading 'ProductID') and I am not sure why since I am accessing it via an id and it should work. How can I properly make my code work and delete the item on click? Here is my attempt:

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Grid, GridColumn as Column } from '@progress/kendo-react-grid';
import { sampleProducts } from './sample-products';

const allInEdit = sampleProducts.map((item) =>
  Object.assign(
    {
      inEdit: true,
    },
    item
  )
);

const deleteItem = (item) => {
  let index = sampleProducts.findIndex(
    (record) => record.ProductID === item.ProductID
  );
  data.splice(index, 1);
  return sampleProducts;
};

const MyCommandCell = () => {
  return (
    <button
      className="k-button k-grid-remove-command"
      onClick={() => deleteItem()}
    >
      Remove
    </button>
  );
};

const App = () => {
  const [data, setData] = React.useState(allInEdit);

  const itemChange = (e) => {
    let newData = data.map((item) => {
      if (item.ProductID === e.dataItem.ProductID) {
        item[e.field || ''] = e.value;
      }

      return item;
    });
    setData(newData);
  };

  return (
    <Grid data={data} editField="inEdit" onItemChange={itemChange}>
      <Column field="ProductID" title="Id" width="50px" editable={false} />
      <Column field="ProductName" />
      <Column field="FirstOrderedOn" editor="date" format="{0:d}" />
      <Column field="UnitsInStock" width="150px" />
      <Column field="Discontinued" width="50px" editor="boolean" />
      <Column cell={MyCommandCell} width="240px" />
    </Grid>
  );
};

ReactDOM.render(<App />, document.querySelector('my-app'));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should move your deleteItem and MyCommandCell functions inside your App component in order to to use setData. You also need to read current row's data from dataItem of current row's item. That value should be passed to the deleteItem function as a prop

You can use this code:

import * as React from "react";
import * as ReactDOM from "react-dom";
import { Grid, GridColumn as Column } from "@progress/kendo-react-grid";
import { sampleProducts } from "./sample-products";

const allInEdit = sampleProducts.map((item) =>
  Object.assign(
    {
      inEdit: true
    },
    item
  )
);

const App = () => {
  const [data, setData] = React.useState(allInEdit);

  const deleteItem = (item) => {
    let newProducts = data.filter(
      (record) => record.ProductID !== item.ProductID
    );
    setData(newProducts);
  };

  const MyCommandCell = (item) => {
    return (
      <button
        className="k-button k-grid-remove-command"
        onClick={() => deleteItem(item.dataItem)}
      >
        Remove
      </button>
    );
  };

  const itemChange = (e) => {
    let newData = data.map((item) => {
      if (item.ProductID === e.dataItem.ProductID) {
        item[e.field || ""] = e.value;
      }

      return item;
    });
    setData(newData);
  };

  return (
    <Grid data={data} editField="inEdit" onItemChange={itemChange}>
      <Column field="ProductID" title="Id" width="50px" editable={false} />
      <Column field="ProductName" />
      <Column field="FirstOrderedOn" editor="date" format="{0:d}" />
      <Column field="UnitsInStock" width="150px" />
      <Column field="Discontinued" width="50px" editor="boolean" />
      <Column cell={MyCommandCell} width="240px" />
    </Grid>
  );
};

ReactDOM.render(<App />, document.querySelector("my-app"));

You can take a look at this sandbox for live working example.

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