import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [movie, setMovie] = useState();
const [director, setDirector] = useState();
const [list, setList] = useState([
{
movie: "",
director: ""
}
]);
const handler = () => {
setList([
...list,
{
movie: movie,
director: director
}
]);
setDirector("");
setMovie("");
};
const removeHandler = (del, index) => {
const newList = list.filter((item) => {
return item.movie !== del;
});
setList([newList]);
};
return (
<div className="App flex justify-between">
<div>
<input value={movie} onChange={(e) => setMovie(e.target.value)} />
</div>
<div style={{ marginTop: "2rem" }}>
<input value={director} onChange={(e) => setDirector(e.target.value)} />
</div>
<button style={{ marginTop: "2rem" }} onClick={handler}>
ADD
</button>
<div>
{list?.map((item) => {
return (
<div>
<ul>
<li key={item.movie}>
{item.movie}, {item.director}
<button onClick={() => removeHandler(item.movie)}>
Remove
</button>
</li>
</ul>
</div>
);
}) || []}
</div>
</div>
);
}
I tried using the filter to filter out the deleted list but it deletes the entire list on Click of remove button here is the codesandbox link https://codesandbox.io/s/relaxed-feather-esbynl?file=/src/App.js:0-1423
Also the first list automatically generate without onSubmit
CodePudding user response:
There are a couple logical errors in the list removal logic. Try the below code.
const removeHandler = (item, index) => {
const newList = list.filter((list) => {
return item !== list.movie;
});
setList(newList);
};
CodePudding user response:
Demo: https://codesandbox.io/s/wonderful-paper-cq0ce7?file=/src/App.js:1025-1300
Remove the brackets from setList([newList])
setList(newList);
As a suggestion: splice
is meant for deleting an item from an array
const removeHandler = (index) => {
setList((prev) => {
const next = [...prev];
next.splice(index, 1);
return next;
});
};
<ul>
{list.map((item, index) => {
return (
<li key={item.movie}>
{item.movie}, {item.director}
<button onClick={() => removeHandler(index)}>Remove</button>
</li>
);
})}
</ul>