So, i’d like to spare time later and want to do a dynamically generated page. For that reason i want to read component data from an object, like this:
layout: {
toolbar: {
components: [
{
type: "Testcomp",
theme: "default",
data: "div1"
},
{
type: "Testcomp",
theme: "pro",
data: "div2"
},
]}}
The component would be dynamically imported, enabled/activated and besides that this is the jsx code supposed to render components dynamically:
render() {
const toolbarComponents = userSession.layout.toolbar.components.map(Component => (
<Component.type theme={Component.theme} data={Component.data} key={this.getKey()} />
));
return (
<div>
<div className="toolbar">
toolbar
{toolbarComponents}
</div>
. . .
</div>
);
}
However i get the following warning in Chrome’s devtool, also the component is not displayed:
Warning: is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.
Warning: The tag is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
What’s wrong with my code?
You are getting those errors because you are not referencing the component itself here, instead using a string as name. So, maybe you need to think another way to create the components dynamically. Like starting with a base component and only give some props and data to it.
// Define above main component or elsewhere then import.
const MyComponent = ( props ) => <div>{props.data}</div>
// Main component
render() {
const toolbarComponents = userSession.layout.toolbar.components.map(
component => <MyComponent theme={component.theme} data={component.data} />
);
return <div className="App">{toolbarComponents}</div>;
}
Here we are not using a type key anymore. If you want to use different components like that, you can create every base component and then use as its name with type key but not with string, directly referencing the component.
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