Element type is invalid: expected a string (for built-in components) or a class/function
Asked Answered
A

24

72
import React from 'react';
import ReactDOM from 'react-dom';
import Map from './components/map/container/map';
import App from './App';
import './index.css';
import shell from './shared/utility/shell';
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware, ConnectedRouter } from 'react-router-redux'
import thunk from 'redux-thunk'
import createHistory from 'history/createBrowserHistory'
import rootReducer from './reducers'
import registerServiceWorker from './registerServiceWorker';
import { Routes } from './config';

const history = createHistory();
const target = document.querySelector('#root')
const initialState = {};
const enhancers = [];
const middleware = [
thunk,
routerMiddleware(history)
 ];

if (process.env.NODE_ENV === 'development') {
const devToolsExtension = window.devToolsExtension;

if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension());
 }
}
const composedEnhancers = compose(
applyMiddleware(...middleware),
  ...enhancers
);
const store = createStore(
 rootReducer,
 initialState,
 composedEnhancers
);
render(
  <Provider store={store}>
   <ConnectedRouter history={history}>
    <div>
     <Routes />
    </div>
   </ConnectedRouter>
  </Provider>,
  target
   )
 registerServiceWorker();
 ReactDOM.render(<App />, document.getElementById('root'));
 registerServiceWorker();

I am trying to call an API from with the help of redux and display its data in a table. I am getting this error. Above is my index.js file.


1. 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.


2. 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.

I have referred to many answers I am not able to recognize the error.

Ananna answered 4/7, 2017 at 4:30 Comment(3)
You are attempting to render something which is not a react component or function. Most likely the problem is your App or Routes since those seem to be the custom ones you are rendering. Double check the exports from those files, and any files they import.Unkindly
like @AustinGreco said, it's an import/export issue. check thisFantasy
I don't know you solved it or not, I was running into the same trouble once, and found out I applied the codes for react-router-redux@next(5.0.0-alphaN) on the older version of react-router-redux.Lorettalorette
J
81

Problem is in the import statements. You have not used curly braces while importing some components like createHistory.

If a component uses a default export like:

export default X

Then you can simply import it like:

import X from './X';

But if you are using a named export like:

export const X=1;

Then you need to import it in curly braces like:

import {X} from './X';

So have a look at your imports. This will resolve your issue.

Jeopardy answered 4/7, 2017 at 4:56 Comment(8)
If in another folder i have mentioned like this...import _map from './container/map'; export { _map as Map }; Do I need to enclose Map in curly braces?Ananna
you can directly write export when declaring class as: export default class Map{ render{ return();}} and import it like import Map from ./classJeopardy
After correcting createHistory I am getting this error._WEBPACK_IMPORTED_MODULE_10_history_createBrowserHistory__.createHistory is not a functionAnanna
Is it because of this ?Ananna
do history package contains createBrowserHisto‌​ry function?Please check it.Jeopardy
refer to this github.com/ReactTraining/react-router/issues/4006Jeopardy
No, putting createHistory in curly braces doesnt work it gives me error at ConnectedrouterAnanna
It wasted my 20-30 minutes and I couldn't figure out where I was doing wrong. Now I know what it was, thanks for the answer :)Soundboard
W
16

I ran into the same problem in my react application. It's definitely your import statements as stated above. I changed:

import {x} from '/x.js' to import x from '/x.js'

and that got the job done

Wessels answered 22/4, 2018 at 17:18 Comment(0)
P
7

I've also run into this error when one of the nested components attempted to render a component that did not exist. Specifically, I attempted to use

<Button ... /> 

a react-native component in React, where I should have been using

<button ... />
Petition answered 9/5, 2018 at 18:9 Comment(0)
B
5

Check you aren't importing your component name in braces like this:

import {SomeComponent} from '../path/to/SomeComponent'; // nope

I realised I had done that and so I changed it to this and it started working:

import SomeComponent from '../path/to/SomeComponent'; // yes

The {} is for selecting from imports with multiple exports like the React components etc, and without you get what the export default is.

Bauer answered 30/7, 2022 at 12:40 Comment(1)
perfect i was exported the component import {SomeComponent} from '../path/to/SomeComponent'; earlier. now its seems fine. ThanksHwu
O
2

It can also be caused from where the entry point is.

In my case, the App.js was calling index.js (where the developer console was identifying the error, and where my RenderDom call was).

However, App.js was referencing a component, and it was within that component that I had the error (a reference to yet another component that did not exist).

Ogpu answered 29/7, 2018 at 22:32 Comment(0)
S
2

For me, I faced this issue when I forget to use react-redux's connect in my export.

So,

changing:

 export default(mapStateToProps, mapDispatchToProps)(ContentTile);

To:

export default connect(mapStateToProps, mapDispatchToProps)(ContentTile);

solved the issue. Really silly mistake

Socher answered 13/11, 2018 at 0:39 Comment(0)
A
2

You may also get this error if a sub-component of the component that the error references has not exported its function/class:

So the problem isn't in the referenced component but in a component that it is importing (which is not referenced in the error text).

Took me a while to find this bugger.

Azral answered 25/8, 2021 at 19:44 Comment(0)
J
2

There are several reasons why this error might occur.

It is definitely related directly to an issue with one of your imports. This could be:

  1. A missing/miss-imported module from a npm package.
  2. A component missing the export or an altogether empty component attempting to be imported.
  3. mixed up named/default export/import
Josettejosey answered 15/11, 2021 at 14:28 Comment(0)
G
1

In my case I solved it changing the components: They were written in functions declarations and I change them by classical Class declarations (class App extends React.Component instead of function App() )

Giff answered 25/9, 2019 at 9:34 Comment(1)
Hey! But why would that matter? It should work both with class and functional components. Did you find the reason?Aglow
R
1

To add to previous replies, you also get this error if one of the components within the component you are trying to import is empty / does not have a correct render method.

Recitation answered 27/9, 2022 at 12:52 Comment(0)
G
1

Old but relevant to the discussion. Upgraded code base to React 18 from React 16 and the dealt the same error. Here is the code in question.

import { Form, InputGroup } from 'react-bootstrap';
export default function Login() {

return (
    <Form >
        <Form.Group>
            <Form.Label>Name</Form.Label>
        </Form.Group>
        <Form.Group>
            <Form.Label>Email</Form.Label>
        </Form.Group>
        <Form.Group style={{ marginBottom: 30 }}>
            <Form.Label>Password</Form.Label>
            <InputGroup>
                <InputGroup.Append>
                    <InputGroup.Text onClick={() => setShowPassword(!showPassword)}>
                    </InputGroup.Text>
                </InputGroup.Append>
            </InputGroup>
        </Form.Group>
    </Form>
);}

Now here is the code that was causing the error. Removed this code and all was good. Almost impossible to track down.

 <InputGroup.Append></InputGroup.Append>

Wasted about 5 hours on this...

Gemagemara answered 12/3 at 5:16 Comment(0)
W
0

As was sayed above, this issue with import. In my case it's was a CSSTransitionGroup import. After npm update the package 'react-transition-group' no longer contains CSSTransitionGroup, but it's contains different exports, like CSSTransition and TransitionGroup. So i just replace line:

import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup'; 

with

import TransitionGroup from 'react-transition-group/TransitionGroup'; 
Wolters answered 4/9, 2018 at 11:0 Comment(0)
W
0

I also had the similar problem while attempting to add routes into my application. I then realised that i was importing { BrowserRouter, Route } from "react-router"; instead of correctly importing it from react-router-dom as below import { BrowserRouter, Route } from "react-router-dom". Thanks to the online community

Womanhater answered 21/3, 2020 at 12:34 Comment(0)
M
0

Make sure you export the component. And if you are already exporting, then you might have missed the default.

export default function App(){
 ...
}
Mcbride answered 21/6, 2021 at 9:59 Comment(1)
i use export default still facing the same issueBorgerhout
F
0

It's a special case, but Recharts threw this error for me when I attempted to put two charts inside one ResponsiveContainer. That is not supported.

Fumigant answered 7/7, 2021 at 14:34 Comment(0)
L
0

Sometimes, It could be as a result of importing from the wrong library, like in my experience, where I should have imported Input component from react native elements.

import { View, ActivityIndicator, Input } from 'react-native';
import { Input, Button } from 'react-native-elements';
Literate answered 7/10, 2021 at 18:7 Comment(0)
C
0

In my case I resolved the problem by removing undefined component. I imported that component from wrong module.

Corsiglia answered 22/10, 2021 at 10:51 Comment(0)
A
0

My problem is solved, the problem was instead of using

import { NavLink } from 'react-router-dom'

I used

import { NavLink } from 'react-dom'

I want to say this, coding includes paying attention to details.

Alialia answered 23/11, 2021 at 9:47 Comment(0)
S
0

I got this error just because import "FlatList" as "Flatlist" in react native expo project. And I spend one and a half hour to realize that :(

Suzetta answered 25/5, 2022 at 22:18 Comment(1)
Disadvantages of not using ESLint or TypeScript 😆Mada
F
0

Well, I got this stupid error, which took me hours to figure out, because I upgraded bootstrap from v4 to v5 and Popover.Title is changed to Popover.Header. I wish the error message could be a little bit more specific.

Fortress answered 9/6, 2023 at 13:21 Comment(0)
P
0

I experienced the same thing and realized createNativeStackNavigator() was missing its parenthesis.

It formerly looked like const Stack = createNativeStackNavigator; instead of const Stack = createNativeStackNavigator();.

Pasadis answered 7/9, 2023 at 16:39 Comment(0)
A
0

I have used the arrow function to crate components. then I changed it to a normal function. then it got solved

Albertson answered 30/10, 2023 at 5:41 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Recto
H
0

I also had this issue but with an other setup. We have an internal dependency with an other team but that dependency doesn't play nice with Jest. So i had to manually mock those components. But i forgot one and this caused this same error but all the components were imported correctly.

Simplified Example:

componentA

import { InternalComponent } from "internal-design-system"

export default const MyComponent = (props) => <InternalComponent/>

componentB

import MyComponent from "MyComponent"

export default MyCompositeComponent = (props) => <div>...<MyComponent>...</div>

Testcase

// Setup before import MyCompositeComponent
jest.mock("internal-design-system", { OtherInternalComponent: () => (<div></div>) }, {virtual: true})

import { render } from '@testing-library/react'
import MyCompositeComponent from "MyCompositeComponent"


describe("MyCompositeComponent", () => {
  it('Renders', () => {
    render(<MyCompositeComponent />)
  })
})

This gives the same 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, or you might have mixed up default and named imports.

    Check the render method of `MyComponent`.

If you add the InteralComponent to the jest mock this resolves the issue.

Hosanna answered 31/5 at 8:53 Comment(0)
U
-1

for me i was trying to route in app.js some component that have problem, so index.js will not render the / because of that in-proper import in app.js

so alwasy make sure components in app.js are working properly

Uneasy answered 13/11, 2019 at 19:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.