Here's my code - as you can see I have just started React.js and programming in general. In this one I'm trying to create a simple to do list and I want to be able to remove some items fromit via clicking on one of list items. I know there is some mistake/lack of code in my onClick but cannot figure how to target a proper id to handle onDeleteHandler... Many thanks ofc.
const App = () => {
const [input, setInput] = useState('')
const [index, setIndex] = useState([])
const id = Date.now()
const onSubmitHandler = (event) => {
event.preventDefault()
if (input.length > 0)
setIndex([...index, { input, id }])
else
alert("Write a proper activity, please!")
setInput('')
}
const onChangeHandler = (event) => {
setInput(event.target.value)
}
const onDeleteHandler = (id) => () => {
let xxx = index.filter(item => item !== id)
setIndex(xxx)
console.log(xxx)
}
return (
<div>
<form className="App" onSubmit={onSubmitHandler}>
<p>MY REACT TO DO LIST</p>
<label>Activity : </label>
<input type="text" value={input} onChange={onChangeHandler}></input>
<input type="submit"></input>
</form>
<ul>
{index.map((item, id) => <li key={id} onClick={onDeleteHandler}>{item.input}</li>)}
</ul>
</div>
)
}
onClick={onDeleteHandler(id)}. Also just be aware that since you are using the array index as the react key and mutating the array you'll likely have unintended side-effects. Use a better react key, something unique to the element being mapped, like a guid.