View on GitHub

marymafa.github.io


layout:post title: Map-in-react date: 2018-03-26 —

Map-in-react

map() function to take an array of numbers and double their values.

example of the map function

function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => <li>{number}</li> ); return ( <ul>{listItems}</ul> ); }

const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById(‘root’) );

There are quite a few parentheses in there thanks to the way map() works

  1. For every item in the array, it gives us the item itself in person and the position of the item in the index.

  2. It creates a new anonymous function (that’s the => part) that receives those two things as a parameter and will return a value of the modified data.

  3. It uses the input element to create some JSX based on the person.

if you use a loop (with map()) you need to give every top-level item printed by that loop a key attribute that identifies it uniquely. The reason for this is called reconciliation and it becomes very important when you make more advanced apps – and can cause some really weird bug. you ever want to add, remove or move items, you’ll need to use a key attribute that doesn’t change when items are moved or rearranged.

if the map() body is too nested, it might be a good time to extract a component.