Search code examples
javascriptreactjsreact-bootstrap

Remove item from list React functional component


the code below displays a list after loading data from a backend, how can I cause the values ​​to be removed from the list and the table to be updated

React Code:

import React, { Component } from "react";
import { fileuploadbolla } from "../../services/file";
import Table from "react-bootstrap/Table";
import { Button } from "reactstrap";

function TableArticoli(props) {
  return (
    <Table striped bordered hover editable>
      <thead>
        <tr>
          <th>N° riga</th>
          <th>Codice</th>
          <th>Descrizione</th>
          <th>Prezzo</th>
          <th>Quantita</th>
          <th>Totale</th>
          <th>Edit</th>
        </tr>
      </thead>
      <tbody>
        {props.list.map((item, i) => {
          return [
            <tr>
              <td>{i}</td>
              <td>{item.codart}</td>
              <td>{item.descrizione}</td>
              <td>{item.prezzo}</td>
              <td>{item.prezzolistino}</td>
              <td>{Number(item.prezzolistino) * Number(item.prezzo)}</td>
              <td>
                <Button size="xs" color="danger">
                  Elimina
                </Button>
              </td>
            </tr>,
          ];
        })}
      </tbody>
    </Table>
  );
}

class UploadFileBolla extends Component {
  constructor(props) {
    super(props);
    this.state = {
      image_file: null,
      image_preview: "",
      listarticoli: [],
    };
  }

  handleImagePreview = (e) => {
    let image_as_base64 = URL.createObjectURL(e.target.files[0]);
    let image_as_files = e.target.files[0];

    this.setState({
      image_preview: image_as_base64,
      image_file: image_as_files,
    });
  };

  handleSubmitFile = async () => {
    if (this.state.image_file !== null) {
      let formData = new FormData();
      formData.append("file", this.state.image_file);
      var listarticoli = await fileuploadbolla(formData, "SONEPAR");
      this.setState({ listarticoli: listarticoli.data });
    }
  };

  render() {
    return (
      <div>
        <input type="file" onChange={this.handleImagePreview} />
        <label>Upload file</label>
        <input type="submit" onClick={this.handleSubmitFile} value="Submit" />
        {this.state.listarticoli.length > 0 ? <TableArticoli list={this.state.listarticoli} /> : <></>}
      </div>
    );
  }
}

export default UploadFileBolla;

Solution

  • You can try this:

    ...
    <Button size="xs" color="danger" onClick={e => this.handleDelete(index,e)}>
        Elimina
    </Button>
    ...
                
    

    And inside the class, you can add:

      handleDelete = (index, e) => {
          this.setState({...,
            listarticoli: this.listarticoli.filter((v, i) => i !== index));
      });