-1

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>
)

}

1
  • You've a curried handler, so just pass the id when attaching the handler, i.e. 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. Commented Oct 26, 2020 at 23:39

1 Answer 1

1

Change

const onDeleteHandler = () => {
    console.log(id)
}

to

const onDeleteHandler = (id) => {
    console.log(id)
}

and then change onClick={onDeleteHandler} to onClick={() => onDeleteHandler(id)}

Take a look at this: https://upmostly.com/tutorials/pass-a-parameter-through-onclick-in-react for more information

Sign up to request clarification or add additional context in comments.

2 Comments

Please check for dupes on here first, and mark as such instead of answering
Ok, stack overflow guided me to this and it answered my question already. Thanks ;) stackoverflow.com/questions/39818569/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.