How to loop in JSX and use as component?

884 views Asked by At

i am trying to import every icon using 'react-icons' package. Its importing fine but when i am trying to use them as a component in my loop it wont display anything.

import * as fa from "react-icons/fa";

{Object.values(fa).forEach((value) => {
  <value/>
})}

I didn't wanted to copy the majority of the code as it has nothing to do, just keep in mind that i am using the object function in return.

6

There are 6 answers

3
Lahcen YAMOUN On BEST ANSWER

That's expected, you're not returning anything, you're just iterating over an array of objects.

For such rendering manipulation just use map, and it's preferable to Capitalize the first letter of the component, and adding a key when iterating to help in the behind the scenes process :

Object.values(fa).map((Value, idx)=>(<Value key={idx}/>))
1
Mechanic On

forEach has no return value, hence nothing will rendered

{Object.values(fa).map((value) => {
  <value/>
})}
0
rzwnahmd On

You might want to use map instead of forEach:

import * as fa from "react-icons/fa";

{Object.values(fa).map((value) => <value />)}
3
Ruan Mendes On

You need to have a variable starting with a capital, and you need to use map sp that a new array is returned, forEach doesn't return anything

Object.values(fa).map((Value) => {
  <Value></Value>
})

See https://www.typescriptlang.org/play/?jsx=2&ssl=4&ssc=1&pln=1&pc=1#code/PIIwVgpgxgLgdANwIYBsCuEDOAKAZkgSjgFskAHbbANVQwIAIBeAPnoG8Aoe+gHhvQjMeAen4ZmHAL4EOsoA

0
Raji Hawa On

Custom JSX tags should start with capital letter and also if you want to render them then use .map() instead of .forEach() because it return an array.

code should be like that:

import * as fa from "react-icons/fa";

{Object.values(fa).map((Icon) => {
  <Icon />
})}
0
keikai On

Some notice points:

  • Change value to Value: use Uppercase first letter for JSX element
  • Change forEach() to map(): for loop in JSX with return
  • Change {} to (): to give a return for each item
  • Add a key (maybe not an index but add one)
{Object.values(fa).map((Value, idx) => (
  <Value key={idx} />
))}

enter image description here