Render React element from object value

Viewed 8568

I want to create an object:

import React from "react";
import { Registration } from "../../";

const RouteObj = {
  Registration: {
    route: "/registration",
    comp: <Registration />
  }
};
export default RouteObj;

And then, in a second file call:

import React from 'react';
import RouteObj from ...

class Thing extends React.Component{
  render() {
    <RouteObj.Registration.comp />
  }
}

When trying this, I get the error:

React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

Is it possible to render React components in this way?

2 Answers

Registration is already a tag (a component), that's why I guess you have to use curly brackets instead.

import React from 'react';
import RouteObj from ...

class Thing extends React.Component{
  render() {
    <div>
      {RouteObj.Registration.comp}
    </div>
  }
}
  1. You've got to export RouteObj correctly, as the default export.

Thus, add this after you declare RouteObj:

export default RouteObj;

You were trying to use something you didn't export, as the error says. It was thus undefined.

  1. You can't create an element from an element, you need to create an element from a component class. So instead, you have to set RouteObj.comp to Registration, the component class itself, not an instance of Registration, <Registration />.

So, instead, this is what comp should be:

comp: Registration
Related