how to explain this I don't know but this is my nightmare. If I learn how to do this, it will be very important for me. I want to map a component and this component uses like <Flag.USA/>
or <Flag.RU/>
. I have an array like this: ["TR","USA","RU"]
. I want to map this component with items of that array.
So, at the end, I want to see something like this:
<Flag.TR/>
<Flag.USA/>
<Flag.RU/>
Here is my code, but it's not working:
const languages = ["TR", "USA", "RU"]
{
languages.map((language, i) => {
<Flags.{language}/> //Here is very importat... I tried like this but didn't work.
})
}
UPDATE:
Flags is a component of a package. country-flag-icons
. If you want to use it, you can use like <Flags.USA/>
and there will be USA flag.
CodePudding user response:
Syntax <Flags.{language}/>
is not allowed in jsx.
You can use createElement
here
https://reactjs.org/docs/react-api.html#createelement
languages.map((language, i) => {
return React.createElement(Flags[language])
})
CodePudding user response:
I think you can create a list of language objects including the exact name of the component, if you want to have a short list:
const languages = [
{key: "TR", comp: <Flag.TR />},
{key: "USA", comp: <Flag.USA />},
{key: "RU", comp: <Flag.RU />},
]
And then, you can loop:
languages.map((language, i) => {
return language.comp
})