Reputation: 69
I'm trying to call my react components with JSX using a string instead of writing the JSX tag directly.
I'm storing tag names in a separate XML file that contains the tag name and other details. 'Tabs' is passed as 'ElementTagString'
<element>
<componentTag>Tabs</componentTag>
</element>
addElement = (ElementTagString) => { // ElementTagString = 'Tabs'
const ElementTag = <ElementTagString/>
return <ElementTag/> // would be equivilent to writing <Tabs/> directly, calling my component.
}
// tabs component defined elsewhere
export function Tabs(props) {
return (
...
);
}
```I'm getting the following errpr:
<Tabs /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.```
I tried the following solutions with no result:
https://stackoverflow.com/a/33471928/9983270
https://reactkungfu.com/2016/11/dynamic-jsx-tags/
https://reactjs.org/docs/jsx-in-depth.html#html-tags-vs.-react-components
Upvotes: 1
Views: 1368
Reputation: 12691
You can't create react components with JSX using a string. What you can do is store your components in an object like this :
import Tabs from './tabs';
import PhotoStory from './photo';
import VideoStory from './video';
const components = {
Tabs: Tabs
Photo: PhotoStory,
Video: VideoStory
};
Then in your function :
addElement = (ElementTagString) => {
const ComponentName = components[ElementTagString];
return <ComponentName />;
}
Upvotes: 3
Reputation: 1990
This is not possible at run-time, as JSX <whatever>
tags are converted into React.createElement
function call.
See my solution with full description of what happens behind the scene here: https://stackoverflow.com/a/55167475/1786034
Upvotes: 0