Ghayas Ud Din
Ghayas Ud Din

Reputation: 335

removing an element in array within map in react

On the click of the span, i want to remove that element from the array and run the map again so that the spans also gets removed. I don't know if the syntax is wrong or what. This is the link to sandbox where I wrote my code. https://codesandbox.io/s/angry-wu-4dd11?file=/src/App.js

import "./styles.css";

export default function App() {
  const data = [{
      name: "Alex",
    },
    {
      name: "John",
    },
    {
      name: "Leo",
    },
    {
      name: "Murphy",
    },
    {
      name: "Alex",
    },
    {
      name: "John",
    },
    {
      name: "Leo",
    },
    {
      name: "Murphy",
    },
  ];

  return ( <
    div className = "App" > {
      data.map(function(val, id) {
        return ( <
          span key = {
            id
          }
          className = "select__item"
          onClick = {
            (e) => {
              data.splice(data.indexOf(val), id + 1);
              console.log(data);
            }
          } >
          {
            val.name
          } < br / > < br / >
          <
          /span>
        );
      })
    } <
    /div>
  );
}

Upvotes: 4

Views: 12068

Answers (2)

AYUSH CHAUDHARY
AYUSH CHAUDHARY

Reputation: 55

function handleRemove(id) {
  // this  work for me 
  const newList = this.state.newList.filter((item) => item.id !== id);
 this.setState({newList});
}

Upvotes: 0

DecPK
DecPK

Reputation: 25408

You should use useState hook in this case, because React won't re-render automatically. You have to tell react externally, one way is to change state and react will rerender components automatically as:

Live Demo

Codesandbox Demo

import { useState } from "react";
import "./styles.css";

export default function App() {
    const [data, setData] = useState([
        {
            name: "Alex",
        },
        {
            name: "John",
        },
        {
            name: "Leo",
        },
        {
            name: "Murphy",
        },
        {
            name: "Alex",
        },
        {
            name: "John",
        },
        {
            name: "Leo",
        },
        {
            name: "Murphy",
        },
    ]);

    const removeItem = (index) => {
        setData(data.filter((o, i) => index !== i));
    };

    return (
        <div className="App">
            {data.map(function (val, id) {
                return (
                    <span
                        key={id}
                        className="select__item"
                        onClick={() => removeItem(id)}>
                        {val.name} <br />
                        <br />
                    </span>
                );
            })}
        </div>
    );
}

Upvotes: 4

Related Questions