相关文章推荐
迷茫的打火机  ·  MySQL 8.0 ...·  1 月前    · 
迷茫的打火机  ·  AiMesh with USB ...·  6 月前    · 
迷茫的打火机  ·  Python : openpyxl ...·  8 月前    · 
迷茫的打火机  ·  Hubs Publishing | ...·  8 月前    · 
迷茫的打火机  ·  JSONPath 支持 | Kubernetes·  11 月前    · 
迷茫的打火机  ·  How to fix PyCharm ...·  11 月前    · 
暗恋学妹的投影仪  ·  《spring ...·  1小时前    · 
从容的排球  ·  异常 ...·  1小时前    · 
无邪的铁板烧  ·  mybatis 操作 oracle 报错 ...·  1小时前    · 
善良的骆驼  ·  ONNX未使用GPU·  2 小时前    · 
好帅的海龟  ·  轻松学pytorch之使用onnx ...·  2 小时前    · 
活泼的生姜  ·  21 Markdown格式 | R语言教程·  2 小时前    · 
App.js
<div> {names.filter(name => name.includes('J')).map(filteredName => ( {filteredName} ))} </div>

Let’s break down the code above.

First, we define our JSX inside by opening a new curly bracket inside of a <div> element. Then, we specify the array for which we want to perform the filter function on.

Because we are performing a function we open up a set of parentheses. This is where we want to set our condition for the filter: in this case, if the element in the array includes the letter ‘J’.

Did you know that you can chain array function in JavaScript, such as filter , map , and reduce ? This can save many lines of code, although it may be difficult to understand for those new to coding.

Finally, we perform another function after the filter function: the map function. This is how we can output the array elements that match the filter condition to the actual user interface inside of li tags.

Let’s see the complete React component code:

App.js
import React from 'react'; const names = ['James', 'John', 'Paul', 'Ringo', 'George']; function App() { return ( {names.filter(name => name.includes('J')).map(filteredName => ( {filteredName} ))} </div> export default App; {people.filter(person => person.age < 60).map(filteredPerson => ( {filteredPerson.name} ))} </div>

It’s very similar to before, just with an extra step of declaring what value inside of the person object we want to filter on:

people.filter(person => person.age < 60)

See above we change the condition to compare the value of age to see if it is less than 60. That filter function will loop through every object in the people array and check the value of age inside each object to check if it is less than 60.

If it is, then we include it in the next step, which is to map those filtered objects out.

Let’s see the entire React component that filters an array of objects by a value inside of the object:

App.js
import React from 'react'; const people = [ name: 'James', age: 31, name: 'John', age: 45, name: 'Paul', age: 65, name: 'Ringo', age: 49, name: 'George', age: 34, function App() { return ( {people.filter(person => person.age < 60).map(filteredPerson => ( {filteredPerson.name} ))} </div> export default App;

Additionally, if you are getting started in React, why not check out my tutorial on how to create your first React component.

 
推荐文章
善良的骆驼  ·  ONNX未使用GPU
2 小时前