I am trying to load a component in React via a prop. It is an icon that I want to pass from the parent component.
Dashboard (parent):
import { Button } from './components'; function App() { return ( <div className="app"> <div className="app__nav"> <Button icon="FiSun" /> <Button icon="FiSun" /> </div> </div> ); }
Button (child):
import React from 'react'; import * as Icon from "react-icons/fi"; import './button.scss'; function Button(props) { return( <button> // Something like this <Icon.props.icon /> </button> ) }
Unfortunately, I can’t find an easy way to make this work since I’m not allowed to use props in the component name.
Advertisement
Answer
Here is a working version :
import * as Icons from "react-icons/fi"; function Button(props) { const Icon = Icons[props.icon]; return <button><Icon/></button>; }
I added an example on stackblitz