Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically rendering component from string: ReactJS

Tags:

reactjs

I was trying to call a component dynamically like this

var Tagname = 'Species';
options.push(<Tagname {...attrs}/>);

And im getting a warning in the console as

Warning: <Species /> is using uppercase HTML. Always use lowercase HTML tags in React.
Warning: The tag <Species> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.

All other codes are working fine. But this component does not working. How can i fix this?

like image 659
Hareesh Avatar asked Feb 19 '18 09:02

Hareesh


1 Answers

Yes you can call the component dynamically, but it should be the component itself not the string.

Like this:

var Tagname = Species;    //component itself, not string
<Tagname {...attrs}/>;

Because JSX will get compiles into React.createElement(Component, props, ...children) and Component will be a string if it a html tag, otherwise a react component.

So if you pass React.createElement("Species", props, ...children), react will treat it as a html tag not a react component.

Update:

You can do one thing, create a map for each component, Like this:

const Map = {
  "componenet1": Component1,
  "componenet2": Component2
}

Now you can access the component using the string key, like this:

let name = "componenet1";
let Tagname = Map[name];
<Tagname {...attrs}/>;
like image 52
Mayank Shukla Avatar answered Oct 19 '22 11:10

Mayank Shukla