ravenousHydra
ravenousHydra

Reputation: 53

How to show number of item added from list in React?

I will be concise. I have a problem when adding a new item to the list, whereas I am trying to figure out how to show a number of an item added. e.g. When I enter some text into the input field and then add an item, I wanna show a number of that item above it.

let renderList = todos.map(todo => {
  return <TodoList numberOrder={todos.map(todo => todo.id).length} 
                   content={todo.content} 
                   key={todo.id} 
                   remove={() => handleDeleteTodo(todo.id)} />
});

The problem is it shows a number, but it increments all items on the list.

Images: First item

Second item

Upvotes: 0

Views: 457

Answers (3)

tgreen
tgreen

Reputation: 1926

Your problem comes from this line: numberOrder={todos.map(todo => todo.id).length}

Basically that is mapping over todos and returning the id and then taking the length of that new array (which is the same as the length of all the todos).

Instead you should use the index of the array that you are mapping over:

let renderList = todos.map((todo, i) => {
  return <TodoList numberOrder={i + 1} 
                   content={todo.content} 
                   key={todo.id} 
                   remove={() => handleDeleteTodo(todo.id)} />
});

I'm adding 1 to the index so that the user will see 1, 2, 3 instead of 0, 1, 2.

Upvotes: 1

Vandesh
Vandesh

Reputation: 6894

Instead of using map, you should use the filter function to filter out the todos with that particular id

numberOrder={todos.filter(todo => todo.id).length}

The map function will always map onto each item of todo and return the length of the todos array.

The whole code -

let renderList = todos.map(todo => {
  return <TodoList numberOrder={todos.filter(todo => todo.id).length} 
                   content={todo.content} 
                   key={todo.id} 
                   remove={() => handleDeleteTodo(todo.id)} />
});

Upvotes: 1

Bhuwan Chandra
Bhuwan Chandra

Reputation: 315

just add an extra parameter in you map function:

let renderList = todos.map((todo, i) => {
// i is the index or array, you can use it for numbering of items as i+1
        return <TodoList numberOrder={todos.map(todo => todo.id).length} content={todo.content} key={todo.id} remove={() => handleDeleteTodo(todo.id)} />
    });

Upvotes: 1

Related Questions