Home > Enterprise >  How can I create JSX elements from an array of React-Icon names?
How can I create JSX elements from an array of React-Icon names?

Time:09-14

import React from "react"
import {GiCard2Spades,GiCard3Spades} from "react-icons/gi"
    
const x = ["GiCard8Spades","GiCard9Spade"]
const y = x.map(item => <item />) //basically to get <GiCard8Spades /> elements
return(<div>{y}</div>)

I know I can right away make array manually with JSX items like but need other way at this situation.

CodePudding user response:

If you're dead set on using strings, you could try

import * as Icons from "react-icons/gi"

const x = ["GiCard8Spades","GiCard9Spade"];
return(<div>{x.map((item) => Icons[item])}</div>)

CodePudding user response:

try this way

    import React from "react"
    import {GiCard2Spades,GiCard3Spades} from "react-icons/gi"
        
    const x = [GiCard8Spades,GiCard9Spade];
    return(<div>{x.map(item => item)}</div>)//basically to get <GiCard8Spades /> elements

This way you will create an array of JSX.Elements, not an array of strings

CodePudding user response:

Yea Im kinda stupid, should just used

import React from "react"
import {GiCard2Spades,GiCard3Spades} from "react-icons/gi"
    
const x = [GiCard8Spades,GiCard9Spades]
const y = x.map(item => React.createElement(item))
return(<div>{y}</div>)
  • Related