9

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?

0

2 Answers 2

6

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>
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to pass props to the RouteObj.Registration.comp component?
@SummmerFort Yes, you can use cloneElement function. React.cloneElement(RouteObj.Registration.comp, props). props is an object with your props.
1
  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

1 Comment

Sorry, I will edit the code, I am exporting it correctly. Wrapping {RouteObj.Registration.comp} works as above!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.