简体   繁体   中英

JSX get Component by string

This is pretty complicated to explain.

I am getting a couple of Icons from a component library as follows:

import { Icons } from my-component-library';`

Let say I've got 3 Icons in there called IconPlus , IconMinus and IconEquals .

I can easily display the IconEquals along with a description prop as follows:

const IconContainer = ({ description ) => (
    <div>
        {description}
        <Icons.IconEquals />
    </div>
)

This works nicely. Now I'm trying to implement a template where I could pass another prop icon to this container which would display the corresponding icon.

Eg. if icon is IconPlus

Then it should render the following:

<div>
    {description}
    <Icons.IconEquals />
</div>

How do I implement my JSX to do that?

This is basically what I've got:

import { Icons } from 'my-component-library'

const IconContainer = ({ description, icon }) => (
    <div>
        {description}
        <Icons.{icon} /> // <---- Obviously that doesn't work
        // ^^^^ But I need something like this
    </div>
);

Is it possible to do this?

您可以这样使用:

<Icons[icon] />

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