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.
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
I doubt this is the pattern you want.
If App knows the name of the component Button should render, you really aren't providing any abstraction by not passing the component reference itself. You might be able to get it to work passing the string like this, but I wouldn't recommend going that route.
Instead, I would pass the component reference to Button like this:
import FiSun from '...';
...
<Button icon={FiSun} />
function Button(props) {
const Icon = props.icon; // Alias as uppercase
return(
<button>
<Icon />
</button>
)
}
Or if you want only the Button component to know about the possible icon types, I would suggest using a normal conditional instead of trying to dynamically create the JSX tag:
function Button(props) {
function renderIcon() {
if (props.icon == 'FiSun') {
return <FiSun />;
} // else etc
}
return(
<button>
{renderIcon()}
</button>
)
}
To provide some stability while still keeping the functionality of allowing the component user to pass in any available icon name, you could do something like this:
function Button(props) {
function renderIcon() {
const I = Icon[props.icon];
if (I) {
return <I />;
}
// Icon is not valid, throw error or use fallback.
if (in_development) {
console.error('[Button]: Invalid prop `icon`. Icon '+props.icon+' does not exist.');
}
return <FallbackIcon />
}
return(
<button>
{renderIcon()}
</button>
)
}