Home > Software design >  Remove item from list React functional component
Remove item from list React functional component

Time:12-02

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;

CodePudding user response:

To remove an item from the list and update the table, you can add a method to handle the removal of an item and pass it to the TableArticoli component as a prop. This method can be called when the user clicks on the delete button, and it should remove the item from the list and update the state of the parent component.

Here is an example of how this can be implemented:

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" onClick={() => props.onDelete(item.codart)}>
                  Elimina
                </Button>
              </td>
            </tr>,
          ];
        })}
      </tbody>
    </Table>
  );
}

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

  // Method to handle the deletion of an item from the list
  handleDelete = (codart) => {
    // Find the index of the item in the list
    const index = this.state.listarticoli.findIndex((item) => item.codart === codart);

    // Create a copy of the list
    const newList = [...this.state.listarticoli];

    // Remove the item from the list
    newList.splice(index, 1);

    // Update the state with the new list
    this.setState({ listarticoli: newList });
  }

  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 ()

CodePudding user response:

To cause the values in the list to be removed and the table to be updated, you can add an event handler to the Elimina button that removes the item from the list and updates the table. Try this:

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

function TableArticoli({ list, onDelete }) {
  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>
        {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" onClick={() => onDelete(item)}>
                  Elimina
                </Button>
              </td>
            </tr>,
          ];
        })}
      </tbody>
    </Table>
  );
}

function UploadFileBolla() {
  const [imageFile, setImageFile] = useState(null);
  const [listarticoli, setListarticoli] = useState([]);

  const handleImagePreview = (e) => {
    let imageAsFiles = e.target.files[0];

    setImageFile(imageAsFiles);
  };

  const handleSubmitFile = async () => {
    if (imageFile !== null) {
      let formData = new FormData();
      formData.append("file", imageFile);
      var listarticoli = await fileuploadbolla(formData, "SONEPAR");
      setListarticoli(listarticoli.data);
    }
  };

  const handleDelete = (item) => {
    // create a copy of the list
    let list = [...listarticoli];

    // find the index of the item to be deleted
    let index = list.indexOf(item);

    // remove the item from the list
    list.splice(index, 1);

    // update the state with the new list
    setListarticoli(list);
  };

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

I also updated to both use functional components for consistency. Hope that is ok.

CodePudding user response:

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));
  });
  

CodePudding user response:

You should pass a function to manipulate the state you have in your HOC component. In that function, you should receive your state and change it, and at the end set state it.

  • Related