How to loop in JSX and use as component?

Viewed 710

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 Answers

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

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}/>))

forEach has no return value, hence nothing will rendered

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

You might want to use map instead of forEach:

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

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

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 />
})}
Related