[reactjs] Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

I am getting this error:

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

This is my code:

var React = require('react')
var ReactDOM =  require('react-dom')
var Router = require('react-router')
var Route = Router.Route
var Link = Router.Link

var App = React.createClass({
  render() {
    return (
      <div>
        <h1>App</h1>
        <ul>
          <li><Link to="/about">About</Link></li>
        </ul>
      </div>
    )
  }
})

var About = require('./components/Home')
ReactDOM.render((
  <Router>
    <Route path="/" component={App}>
      <Route path="about" component={About} />
    </Route>
  </Router>
), document.body)

My Home.jsx file:

var React = require('react');
var RaisedButton = require('material-ui/lib/raised-button');

var Home = React.createClass({
  render:function() {
    return (
        <RaisedButton label="Default" />
    );
  },
});

module.exports = Home;

This question is related to reactjs react-router

The answer is


It means some of your imported Components are wrongly declared or nonexistent

I had a similar issue, I did

import { Image } from './Shared'

but When I looked into the Shared file I didn't have an 'Image' component rather an 'ItemImage' Component

import { ItemImage } from './Shared';

This happens when you copy code from other projects ;)


Just as a quick addition to this. I was having the same problem and while Webpack was compiling my tests and the application was running fine. When I was importing my component into the test file I was using the incorrect case on one of the imports and that was causing the same error.

import myComponent from '../../src/components/myComponent'

Should have been

import myComponent from '../../src/components/MyComponent'

Note that the import name myComponent depends on the name of the export inside the MyComponent file.


In my case I was using the default export, but not exporting a function or React.Component, but just a JSX element, i.e.

Error:

export default (<div>Hello World!</div>)

Works :

export default () => (<div>Hello World!</div>)

I was having the same issue and realized that I was providing an Undefined React component in the JSX markup. The thing is that the react component to render was dynamically calculated and it ended up being undefined!

The error stated:

Invariant Violation: Element 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. Check the render method of C.,

The example producing this error:

_x000D_
_x000D_
var componentA = require('./components/A');_x000D_
var componentB = require('./components/B');_x000D_
_x000D_
const templates = {_x000D_
  a_type: componentA,_x000D_
  b_type: componentB_x000D_
}_x000D_
_x000D_
class C extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
  }_x000D_
  _x000D_
  // ..._x000D_
  _x000D_
  render() {_x000D_
    //Let´s say that depending on the uiType coming in a data field you end up rendering a component A or B (as part of C)_x000D_
    const ComponentTemplate = templates[this.props.data.uiType];_x000D_
    return <ComponentTemplate></ComponentTemplate>_x000D_
  }_x000D_
  _x000D_
  // ..._x000D_
}
_x000D_
_x000D_
_x000D_

The problem was that an invalid "uiType" was provided and therefore this was producing undefined as result:

_x000D_
_x000D_
templates['InvalidString']
_x000D_
_x000D_
_x000D_


In my case, one of the exported child module was not returning a proper react component.

const Component = <div> Content </div>;

instead of

const Component = () => <div>Content</div>;

The error shown was for the parent, hence couldn't figure out.


I got this error in react routing, problem was that I was using

<Route path="/" component={<Home/>} exact />

but it was wrong route requires component as a class/function so I changed it to

<Route path="/" component={Home} exact />

and it worked. (Just avoid the braces around the component)


I got this error while upgrading all libs to latest version

in older version following are imports

import { TabViewAnimated, TabViewPagerPan } from 'react-native-tab-view';

but in new version they are replaced with following

import { TabView, PagerPan } from "react-native-tab-view";

So be check proper all your import are available by using control click


In my case, that was caused by wrong comment symbols. This is wrong:

<Tag>
    /*{ oldComponent }*/
    { newComponent }
</Tag>

This is correct:

<Tag>
    {/*{ oldComponent }*/}
    { newComponent }
</Tag>

Notice the curly brackets


I had the same issue and the issue was some js files were not included in the bundling of that specific page. Try including those file and problem might be fixed. I did this:

.Include("~/js/" + jsFolder + "/yourjsfile")

and it fixed up the issue for me.

This was while I was using React in Dot NEt MVC


@Balasubramani M saved me here. Wanted to add one more to help people. This is the problem when you're gluing too many things together and being cavalier with versions. I updated a version of material-ui and need to change

import Card, {CardContent, CardMedia, CardActions } from "@material-ui/core/Card"; 

to this:

import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';

And in my case I was just missing a semicolon at the import-decleration in one of my sub modules.

Fixed it by changing this:

import Splash from './Splash'

to this:

import Splash from './Splash';

Don't get surprised by the list of answers for a single question. There are various causes for this issue;

For my case, the warning was

warning.js:33 Warning: 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. Check your code at index.js:13.

Followed by the error

invariant.js:42 Uncaught Error: Element 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.

I couldn't understand the error since it doesn't mention any method or file name. I was able to resolve only after looking at this warning, mentioned above.

I have the following line at the index.js.

<ConnectedRouter history={history}>

When I googled for the above error with the keyword "ConnectedRouter" I found the solution in a GitHub page.

The error is because, when we install react-router-redux package, by default we install this one. https://github.com/reactjs/react-router-redux but not the actual library.

To resolve this error, install the proper package by specifing the npm scope with @

npm install react-router-redux@next

You don't need to remove the wrongly installed package. It will be automatically overwritten.

Thank you.

PS: Even warning helps you. Don't neglect warning just looking at the error alone.


If you get this error, it might be because you're importing link using

import { Link } from 'react-router'

instead, it might be better to use

import { Link } from 'react-router-dom'
                      ^--------------^

I believe this is a requirement for the react router version 4


I'm getting almost the same error:

Uncaught (in promise) Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

I was trying to import a pure functional component from another node library my team has developed. To fix it, I had to change to an absolute import (referencing the path to the component inside node_modules) from

import FooBarList from 'team-ui';

to

import FooBarList from 'team-ui/lib/components/foo-bar-list/FooBarList';


By mistake i tried to import Container and Content from react-native instead of native-base.

Error because of this line:

import { ActivityIndicator, RefreshControl,  StyleSheet, View, Keyboard, Container, Content } from 'react-native';

Below is the code fix:

import { ActivityIndicator, RefreshControl,  StyleSheet, View, Keyboard } from 'react-native';
import { Container, Content} from 'native-base';

you need export default or require(path).default

var About = require('./components/Home').default

Given your error of:

'Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object'

You have 2 options:

  1. Your export file can have the word default as in export default class ____.... Then your import will need to avoid using {} around it. As in import ____ from ____

  2. Avoid using the default word. Then your export looks like export class ____... Then your import must use the {}. Like import {____} from ____


I have the same error : ERROR FIX !!!!

I use 'react-router-redux' v4 but she's bad.. After npm install react-router-redux@next I'm on "react-router-redux": "^5.0.0-alpha.9",

AND IT'S WORK


Another possible solution, that worked for me:

Currently, react-router-redux is in beta and npm returns 4.x, but not 5.x. But the @types/react-router-redux returned 5.x. So there were undefined variables used.

Forcing NPM/Yarn to use 5.x solved it for me.


I've discovered another reason for this error. It has to do with the CSS-in-JS returning a null value to the top-level JSX of the return function in a React component.

For example:

const Css = styled.div`
<whatever css>
`;
export function exampleFunction(args1) {
  ...
  return null;
}

export default class ExampleComponent extends Component {
...
render() {
const CssInJs = exampleFunction(args1);
  ...
  return (
    <CssInJs>
      <OtherCssInJs />
      ...
    </CssInJs>
  );
}

I would get this warning:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: null.

Followed by this error:

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: null.

I discovered it was because there was no CSS with the CSS-in-JS component that I was trying to render. I fixed it by making sure there was CSS being returned and not a null value.

For example:

const Css = styled.div`
<whatever css>
`;
export function exampleFunction(args1) {
  ...
  return Css;
}

export default class ExampleComponent extends Component {
...
render() {
const CssInJs = exampleFunction(args1);
  ...
  return (
    <CssInJs>
      <OtherCssInJs />
      ...
    </CssInJs>
  );
}

In my case it ended up being the outer component imported like this:

import React, { Component } from 'react';

and then declared like:

export default class MyOuterComponent extends Component {

where an inner component imported the React bare:

import React from 'react';

and dotted into it for declaration:

export default class MyInnerComponent extends ReactComponent {


I got this by doing import App from './app/'; expecting it to import ./app/index.js, but it instead imported ./app.json.


I had an issue with React.Fragment, because the version of my react was < 16.2, so I got rid of it.


In my case, the import was happening implicitly due to a library.

I managed to fix it by changing

export class Foo

to

export default class Foo.


For me it was that my styled-components were defined after my functional component definition. It was only happening in staging and not locally for me. Once I moved my styled-components above my component definition the error went away.


exporting at the bottom of the file might solve it.

const IndicatorCloak = (props) => { ... }
export default IndicatorCloak;

I was the same problem because I did import incorrect library, so i checked the documentation from the library and the route was changed with the new versión, the solution was this:

import {Ionicons} from '@expo/vector-icons';

and I was writing the incorrect way:

import {Ionicons} from 'expo';

In addition to import/export issues mentioned. I found using React.cloneElement() to add props to a child element and then rendering it gave me this same error.

I had to change:

render() {
  const ChildWithProps = React.cloneElement(
    this.props.children,
    { className: `${PREFIX}-anchor` }
  );

  return (
    <div>
      <ChildWithProps />
      ...
    </div>
  );
}

to:

render() {
  ...
  return (
    <div>
      <ChildWithProps.type {...ChildWithProps.props} />
    </div>
  );
}

See the React.cloneElement() docs for more info.


In my case, it was the meta tags.

I was using

const MetaTags = require('react-meta-tags');

I guess MetaTags is a default export, So changing to this solved it for me, took hours to figure out which one was causing it.

const { MetaTags } = require('react-meta-tags');

In my case I had written const Tab = createBottomTabNavigator instead of const Tab = createBottomTabNavigator()


Have you just modularized any of your React components? If yes, you will get this error if you forgot to specify module.exports, for example:

non-modularized previously valid component/code:

var YourReactComponent = React.createClass({
    render: function() { ...

modularized component/code with module.exports:

module.exports = React.createClass({
    render: function() { ...

https://github.com/rackt/react-router/blob/e7c6f3d848e55dda11595447928e843d39bed0eb/examples/query-params/app.js#L4 Router is also one of the properties of react-router. So change your modules require code like that:

  var reactRouter = require('react-router')
  var Router = reactRouter.Router
  var Route = reactRouter.Route
  var Link = reactRouter.Link

If you want to use ES6 syntax the link use(import), use babel as helper.

BTW, to make your code works, we can add {this.props.children} in the App, like

render() {
  return (
    <div>
      <h1>App</h1>
      <ul>
        <li><Link to="/about">About</Link></li>
      </ul>
      {this.props.children}
    </div>

  )
}

I ran into this error when I had a .jsx and .scss file in the same directory with the same root name.

So, for example, if you have Component.jsx and Component.scss in the same folder and you try to do this:

import Component from ./Component

Webpack apparently gets confused and, at least in my case, tries to import the scss file when I really want the .jsx file.

I was able to fix it by renaming the .scss file and avoiding the ambiguity. I could have also explicitly imported Component.jsx


Had similar issue with React Native latest versions 0.50 and up.

For me it was a difference between:

import App from './app'

and

import App from './app/index.js'

(the latter fixed the issue). Took me hours to catch this weird, hard to notice nuance :(


The problem can also be an alias used for a default export.

Change

import { Button as ButtonTest } from "../theme/components/Button";

to

import { default as ButtonTest } from "../theme/components/Button";

solved the issue for me.


In my case, it took me a bunch of time to search out and checked may ways but only fixed by this way: remove "{", "}" when importing a custom component:

import OrderDetail from './orderDetail';

My wrong way was:

import { OrderDetail } from './orderDetail';

Because in the orderDetail.js file, I exported OrderDetail as the default class:

class OrderDetail extends Component {
  render() {
    return (
      <View>
        <Text>Here is an sample of Order Detail view</Text>
      </View>
    );
  }
}

export default OrderDetail;

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to react-router

React : difference between <Route exact path="/" /> and <Route path="/" /> You should not use <Link> outside a <Router> React Router Pass Param to Component Detect Route Change with react-router What is the best way to redirect a page using React Router? No restricted globals React-router v4 this.props.history.push(...) not working How to pass params with history.push/Link/Redirect in react-router v4? How to use Redirect in the new react-router-dom of Reactjs How to implement authenticated routes in React Router 4?