How to load react component based on prop value

Viewed 89

I am using icon component with '@fluentui/react-northstar' library as as below

import { QnaIcon } from '@fluentui/react-northstar'
const Example1 = () => (
  <>
    <QnaIcon size="large" />
  </>
) 

Now I have to dynamically load the icon component when icon name is come from prop something like this

import React from 'react'
import { Button, TeamCreateIcon   } from '@fluentui/react-northstar' 

const Example2 = ({iconName}) => {
 
const MyIcon = <iconName /> ; //here I need to convert string to component 

return (
  <div >
     <Button icon={<TeamCreateIcon />} title="Create" />
     // Here I need set it
     <Button icon={<MyIcon />} title="Create" />    
  </div>
)} 
<Example2 iconName='QnaIcon' />  

code https://codesandbox.io

2 Answers

I am Brazilian and therefore I speak Portuguese, but I will use the translator to try to help you.

What you can do is the following:

import React from 'react'
import { Button, TeamCreateIcon   } from '@fluentui/react-northstar' 

const Example2 = ({iconName}) => {

const ICONS = {
  iconLike: <YourLikeIcon/>,
  iconMenu: <YourMenuIcon/>,
}

return (
  <div >
     <Button icon={<TeamCreateIcon />} title="Create" />
     // Here I need set it
     <Button icon={ICONS[iconName]} title="Create" />    
  </div>
)} 

But you must be careful with iconName, because if it is not correct it can give an error. To prevent you can do some tests beforehand.

I would rather do it in a different way. I would pass the component itself as props to Example2

<Example2>
  <Icon/>
</Example2>

In the actual component, I would use props.children, which contains the child component that we mentioned as above

import React from 'react'

const Example2 = () => {
 

return (
  <div >
     <Button icon={props.children} title="Create" />
     <Button icon={<MyIcon />} title="Create" />    
  </div>
)} 

EDIT

Including the codesandbox link as well

https://codesandbox.io/s/fluent-ui-example-forked-p5lkk?file=/example.js

Related