Is it possible to generate a component tag itself from a props? Please help
Component is
<AvatarButtonIconB variant="light" iconname="Avatarcircleuser" />
inside above component I wanted to generate a component tag "Avatarcircleuser" by <{props.iconname} /> like
<Avatarcircleuser />
https://codesandbox.io/s/load-component-tag-name-from-props-t3cmtq
CodePudding user response:
Instead of passing the name of the component as a string, pass the component itself. So in the parent component, import the "avatar" component:
import Avatarcircleuser from "./Avatarcircleuser ";
And pass it to the child component:
<AvatarButtonIconB variant="light" icon={Avatarcircleuser} />
Then in AvatarButtonIconB
you would simply output that prop:
<>{props.icon}</>
CodePudding user response:
No. This is not possible, because a component needs have specified content. I'm not sure what your goal is in generating a component tag, because when it's compiled, it will just be whatever elements are in the component.
If you want a component to be identified differently than another, just add a key prop. This is something that's specifically important when using an array to create components for each item in the array. An easy way to do this is using a random id generator package like random-key.