James Hetfield
James Hetfield

Reputation: 53

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.

Upvotes: 1

Views: 169

Answers (3)

BrendanCoca
BrendanCoca

Reputation: 41

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

Upvotes: 1

James Hetfield
James Hetfield

Reputation: 53

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

Upvotes: 0

Guilherme Moraes
Guilherme Moraes

Reputation: 149

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

Upvotes: 0

Related Questions