React, using .map with index Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of React, using .map with index without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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?

Answer

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
We are here to answer your question about React, using .map with index - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji