Rendering Lists
You are going to run in to situations where you may need the same component but use different data. You can store data in objects and arrays and use methods like map() and filter(0) to render lists of components from them.
Mapping an Array
How to Map an Array
Step 1: Move your data in to an array
const people = ['Iris van Ollefen','John Doe','Jane Doe','James Bond'];
Step 2: Map the array items
You can do this by mapping the array items in to a new array of JSX nodes and give that a new name.
const listItems = people.map(person => <li>{person}</li>
Step 3: Return the new array
You can return the new array from your component wrapped in an element.
return <ul>{listItems}</ul>
Filtering an array
Why would you filter an array?
If you only want to show a few of the items you have in your array, you can filter that array so it only shows the filtered few items.
The `filter()` method takes an array of items, passes them through a test and returns a new array of only those items that passed the test.
How to filter an array
For this example, we'll use a more structured version of the people array:
const people = [
{
id: 0,
name: 'Iris van Ollefen',
profession: 'intern',
},
{
id: 1,
name: 'John Doe',
profession: 'tech lead',
},
{
id: 2,
name: 'Jane Doe',
profession: 'developer',
},
{
id: 3,
name: 'James Bond',
profession: 'secret agent',
}
];
Step 1: Create a new array
You want to create a new array for the filtered result and filter the result.
const interns = people.filter(person =>person.profession === 'intern');
Step 2: Map over the filtered array
const listItems = interns.map((person) => {
// whatever you want to happen
});
Step 3: Return the new original array
return <ul>{listItems}</ul>;
About the key
Every array item needs a `key`. This can be a string or a number that uniquely identifies it among other items in that array.
Data provided by keys
Data that comes from a database: If your data comes from a database, you can use the keys or ID's that are unique by nature and come from the database itself.
Locally generated data: This data is generated and persisted locally.
Rules when using keys
The key must be unique among siblings.
Keys can not change.
Why do we need keys?
A key is something unique, nothing else is as unique as this.
A few notes
When returning an expression after =>
you do not need a return
statement, since this is done by the arrow function. However, if they contain curly braces, they do need a return
statement.