I have a string which contains a name of the Class (this is coming from a json file). This string tells my Template Class which layout / template to use for the data (also in json). The issue is my layout is not displaying.
Home.jsx:
//a template or layout.
var Home = React.createClass({
render () {
return (
<div>Home layout</div>
)
}
});
Template.jsx:
var Template = React.createClass({
render: function() {
var Tag = this.props.template; //this is the name of the class eg. 'Home'
return (
<Tag />
);
}
});
I don't get any errors but I also don't see the layout / Home Class. I've checked the props.template and this logs the correct info. Also, I can see the home element in the DOM. However it looks like this:
<div id='template-holder>
<home></home>
</div>
If I change following line to:
var Tag = Home;
//this works but it's not dynamic!
Any ideas, how I can fix this? I'm sure it's either simple fix or I'm doing something stupid. Help would be appreciated. Apologies if this has already been asked (I couldn't find it).
Thanks, Ewan
When you use JSX you can either render HTML tags (strings) or React components (classes).
When you do var Tag = Home, it works because the JSX compiler transforms it to:
with the variable Tag in the same scope and being a React class.
When you do
you are doing
But "aClassName" is not a valid HTML tag.
Look here
This will not work:
However, this will:
So you simply need to find a way to map between the string
"Home"
and the component classHome
. A simple object will work as a basic registry, and you can build from there if you need more features.If you can live with having all your components in one module, then this works without having to manually map your classes to a dictionary:
The wildcard import statement is already a dictionary and the code works like the registry in the previous answer.
Actually, I think you could work with multiple modules with one additional mapping:
I would totally do this. In fact I think I am.
I wanted to know how to create React classes dynamically from a JSON spec loaded from a database and so I did some experimenting and figured it out. My basic idea was that I wanted to define a React app through a GUI instead of typing in code in a text editor.
This is compatible with React 16.3.2. Note
React.createClass
has been moved into its own module.Here's condensed version of the essential parts:
You can see a more complete example here:
https://github.com/brennancheung/02-dynamic-react/blob/master/src/commands/tests/createClass.test.js
I had the same problem, and found out the solution by myself. I don't know if is the "best pratice" but it works and I'm using it currently in my solution.
You can simply make use of the "evil" eval function to dynamically create an instance of a react component. Something like:
Then, just call it where you want:
If it fits your needs, maybe you can consider something like this.
Hope it helps.