Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect casing error with dynamically rendered component in React

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?

like image 644
inspiral Avatar asked May 23 '18 21:05

inspiral


1 Answers

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.

like image 78
devserkan Avatar answered Sep 21 '22 05:09

devserkan