React, using .map with index
I have a simple React component like so:
import React from 'react';
const ListPage = ({todos}) => (
<div>
<h6>todos</h6>
<ul>
{todos.map(({todo, index}) => (
<li key={index}>{todo}</li>
))}
</ul>
</div>
)
ListPage.propTypes = {
todos: React.PropTypes.array,
};
export default ListPage;
I can see that the docs for Array.prototype.map() shows that the second argument is index, next to currentValue. How does one alter the existing code to pick up the second argument?
Solution 1:
You need to to this:
todos.map((key, index) => { ... })
without object brackets for arguments.
({todo, index}) => { ... }
- that syntax means that you want to get properties todo
and index
from first argument of function.
You can see syntax here:
Basic syntax
(param1, param2, …, paramN) => { statements } (param1, param2, …, paramN) => expression // equivalent to: => { return expression; } // Parentheses are optional when there's only one parameter: (singleParam) => { statements } singleParam => { statements } // A function with no parameters requires parentheses: () => { statements }
Advanced syntax
// Parenthesize the body to return an object literal expression: params => ({foo: bar}) // Rest parameters and default parameters are supported (param1, param2, ...rest) => { statements } (param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements } // Destructuring within the parameter list is also supported var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; f(); // 6
Solution 2:
Here is a example base on @Timur Bilalov answer to make easy to understand
var materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
materials.map((material,index) => console.log(index +" = " + material + " = " + materials[index]));
Output
"0 = Hydrogen = Hydrogen"
"1 = Helium = Helium"
"2 = Lithium = Lithium"
"3 = Beryllium = Beryllium"
Reference
https://reactjs.org/docs/lists-and-keys.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Hope it help
Solution 3:
Be careful, you should not use the index as a key if the list is dynamic, it is antipattern and could lead into troubles.
You should use the index as a key ONLY if you are sure you will not have to delete or add items to your todos after creation (it could still be acceptable if you add items but only at the end of the list, and still never delete). Otherwise React might run into problems reconciliating your children.
The best practise is to add an "id" to all your todos (incremental or UUID) and use it as the key for all the react lists that need it.