简体   繁体   中英

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

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM