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>
  );
}
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
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>
    );
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With