Asking
Asking

Reputation: 4200

Delete a value from the list in ReactJs

I am using antd, upload component.

import React, { useState } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Upload, Button } from "antd";
import { UploadOutlined } from "@ant-design/icons";

const fileList = [
  {
    uid: "-1",
    name: "xxx.png",
    status: "done",
    url:
      "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png",
    thumbUrl:
      "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
  },
  {
    uid: "-2",
    name: "yyy.png",
    status: "error"
  }
];

console.log(fileList);
const Demo = () => {
  const [state, setState] = useState([...fileList]);
  const add = () => {
    setState([
      ...state,
      {
        uid: "-3",
        name: "xxdx.png",
        status: "done",
        url:
          "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png",
        thumbUrl:
          "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
      }
    ]);
  };
  return (
    <>
      <button onClick={add}>add</button>
      <Upload
        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
        listType="picture"
        fileList={[...state]}
      >
        <Button icon={<UploadOutlined />}>Upload</Button>
      </Upload>
    </>
  );
};

ReactDOM.render(<Demo />, document.getElementById("container"));

I want to delete an image from the list bellow uploader, but something is wrong and it does not work.
Why deleting images does not work?
demo: https://codesandbox.io/s/pictures-with-list-style-antd4130-forked-umels?file=/index.js:0-1382

Upvotes: 0

Views: 119

Answers (1)

JAM
JAM

Reputation: 6205

You are missing an onRemove prop on the Upload component to handle removal of items.

<Upload
  // ...
  onRemove={(file) => {
    // Remove the file from the state
    setState(state.filter(item => item.uid !== file.uid))
  }}
>

Upvotes: 1

Related Questions