-1

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

PRANAV
  • 1,009
  • 5
  • 16
  • 36

2 Answers2

0

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}</>
David
  • 208,112
  • 36
  • 198
  • 279
0

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.

andrilla
  • 339
  • 1
  • 13
  • Actually I have a group of icons which I have imported as import {ReactComponent as Avatarimage} from "../icon1.svg" so trying to call any imported icon from the group as icon="icon1" props to component , the icon itself as a component like – PRANAV Jul 27 '22 at 15:35
  • Maybe that's what you meant to explain in your question, then—but still all you're really doing is using ReactComponent and renaming it for your own reference. One it's all compiled it's not going to say "Avatarimage" as the element. – andrilla Jul 28 '22 at 16:47