Hello everyone, it's been a really long while. Happy new year, firstly!
I've decided to restart doing some daily code challenges again just to refresh my memory and what better way to go about it then to do some Todo project. A simple project that can add, remove and move todo items from a list.
I'll just start off by saying this is completely from an observatory standpoint. It's an interesting one. I got stuck on it for a few minutes, but it's interesting nonetheless.
So here's the frontend code.
<p>Todos</p>
<ul>
{
todosArr.map((todo, id) => {
return(
<div key={id}>
<li key={id}>{todo}</li>
<button onClick={(id) => onRemove(id)}>Remove</button>
</div>
)
})
}
</ul>
The above code renders the Todos section like this.
So, from here, I would like to implement the "Remove" button. The way I'm going to go about doing it, is to get the id
of each row or text, pass it to a removeItem
function and remove it from there.
So, you can roughly see what I'm trying to do here. Get the id
and pass it to a function.
todosArr.map((todo, id) => {
return(
<div key={id}>
<li key={id}>{todo}</li>
<button onClick={(id) => onRemove(id)}>Remove</button>
</div>
)
})
This is my onRemove
function.
const onRemove = (id) => {
console.log(`id: ${id}`)
console.log(id)
let tmpTodos = [...todosArr]
tmpTodos.splice(id, 1);
setTodosArr(tmpTodos)
}
When I click on the "Remove" button, this is what it outputs.
So, as you can see, it does not output the id
, but instead outputs the SyntheticBaseEvent
.
Let's say, I were to edit the code as such. I remove the id
from the onRemove
callback.
So now, instead of
<button onClick={(id) => onRemove(id)}>Remove</button>
it becomes,
<button onClick={() => onRemove(id)}>Remove</button>
When I click on the "Remove" button, the function is now correct.
So, as it turns out, doing it like this,
<button onClick={(id) => onRemove(id)}>Remove</button>
means you're passing the Event
object to the onRemove
function.
Ok, cool.
How about we go about it a different way? Let's make it clearer. How about this code?
<button onClick={(event) => onRemove(event, id)}>Remove</button>
We will explicitly define it as such, which means we would have to modify our onRemove
code as well.
It works.
Let's change our code again to this.
<button onClick={onRemove}>Remove</button>
Our onRemove
function will also change to this.
So, what does it output?
Interesting. It outputs the event
object.
Alright, so as a recap, all these work.
<button onClick={() => onRemove(id)}>Remove</button>
<button onClick={(event) => onRemove(event, id)}>Remove</button>
Top comments (0)