I’m building a to-do list and I want each list item to have a number, starting from 1. I’m using the useState hook on the counter but I can’t figure out how to add new items to the array every time I click on a button. I haven’t coded in months and I’m really rusty.
I want to make it so each time I add a list item, it adds its number to the left. The first item would have 1, the second 2, etc..
Answer:
This is really bad practice:
What you want to do is use the index param that Javascript map function gives you: Good practice
Output
Now if want the index to start at 1, you can simply add +1 to index
Output
Since the index values are unique, you could use that to your benefit when performing other actions such as deleting etc. Usually you add the key attribute to the individual child values according to the official React documentation as follows
where key is a unique value.
Also, change your variable names to something more meaningful.
I’d suggest changing todo to plurial todos.
Your final code should look like this:
If you have better answer, please add a comment about this, thank you!