• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Generate a new item in an array in React?

Resolved: Generate a new item in an array in React?

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

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!

javascript reactjs
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How to get Union type from an array of objects in Flow?

24/03/2023

Resolved: Modify entity using Action in C#

24/03/2023

Resolved: How to give rank on datetime column group by another column with userid in it

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.