Search code examples
reactjsreact-props

How to use call an item from a library based on props in React?


I would like to allow a user to choose their Icon from AntD Icons to display on my component.

Here are the docs for AntD Icons

https://ant.design/components/icon/

I import the icons (to have access to all of them) via import * as Icons from "@ant-design/icons";

For example if someone passes in a prop of icon="DownOutlined" I want to display the Icon from AntD. In order to display that icon I could hardcode <Icons.DownOutlined />, but how I do I change what comes after the . based on the props?

I have tried:

import * as Icons from "@ant-design/icons";

const Comp = (props) => {

  const { 
         icon: "DownloadOutlined"
         label: "Hello World" 
         } = props;

return <p>{label}<Icons.`${icon}` /></p>

}

and I have also tried <Icons[icon] /> neither of which work.


Solution

  • This works:

    import * as Icons from "@ant-design/icons";
    
    const Comp = (props) => {
      const { icon: "DownloadOutlined", label: "Hello World" } = props;
      const DownloadOutlinedIcon = Icons[icon];
      
      return <p>{label}<DownloadOutlinedIcon/></p>
    }