This is the code,
JavaScript
x
45
45
1
import "./styles.css";
2
import Ank from "./Ank";
3
import { useState, useRef, useEffect } from "react";
4
export default function App() {
5
const [array, setArray] = useState(
6
JSON.parse(localStorage.getItem("notes")) ?? []
7
);
8
useEffect(() => {
9
localStorage.setItem("notes", JSON.stringify(array));
10
}, [array]);
11
const Add = () => {
12
setArray((e) => {
13
return [e, one.current.value];
14
});
15
};
16
const deleting = (e) => {
17
setArray((e1) => {
18
return e1.filter((e2, index) => {
19
return index !== e - 1;
20
});
21
});
22
};
23
const one = useRef(null);
24
return (
25
<>
26
<div className="App">
27
<h1>Hello CodeSandbox</h1>
28
<div className="align">
29
<input ref={one} />
30
<br />
31
<br />
32
<button onClick={Add}>Add</button>
33
</div>
34
<div className="align">
35
{array.map((e, index) => {
36
return (
37
<Ank key={index} onSelect={deleting} index={index + 1} name={e} />
38
);
39
})}
40
</div>
41
</div>
42
</>
43
);
44
}
45
Please check the function deleting
in the filter section I am trying to delete the elemt from the array
using setarray
.
This is the codesandbox link
https://codesandbox.io/s/silly-neumann-b0foos?file=/src/App.js:0-1072
Advertisement
Answer
e
is an object having index
as prop… so its e.index
JavaScript
1
8
1
const deleting = (e) => {
2
setArray((e1) => {
3
return e1.filter((e2, index) => {
4
return index !== e.index - 1; // here
5
});
6
});
7
};
8