javascript / beginner
Snippet
Filtering Data before Rendering
The .filter() method creates a new array with all elements that pass a test. You can use it in React to show only specific data to the user.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
function FruitList() {const fruits = ['Apple', 'Banana', 'Avocado', 'Berry'];const filteredFruits = fruits.filter(fruit => fruit.startsWith('A'));return (<ul>{filteredFruits.map(fruit => (<li key={fruit}>{fruit}</li>))}</ul>);}
react
Breakdown
1
fruits.filter(fruit => fruit.startsWith('A'))
Creates a new array containing only fruits that start with the letter 'A'.