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
In the case of the class component, React creates an instance of the class using the new keyword: const instance = new Component(props); This instance is an object. When we say a component is a class, what we actually mean is that it is an object.
In React, keys are like a Special String attribute that is included in the Creation of List of Elements. Keys play a great significance in React, and they help us to know what are the items in the given list of elements that have changed or are updated or removed.
The React Constructor is a method that's automatically called during the creation of an object from a class. Simply put, the constructor, like its name, is a great tool to build things. Click here to understand more about usereducer used in React.
A React Element is what gets returned from components. It's an object that virtually describes the DOM nodes that a component represents. With a function component, this element is the object that the function returns. With a class component, the element is the object that the component's render function returns.
This will not work:
var Home = React.createClass({ ... }); var Component = "Home"; React.render(<Component />, ...);
However, this will:
var Home = React.createClass({ ... }); var Component = Home; React.render(<Component />, ...);
So you simply need to find a way to map between the string "Home"
and the component class Home
. A simple object will work as a basic registry, and you can build from there if you need more features.
var components = { "Home": Home, "Other": OtherComponent }; var Component = components[this.props.template];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With