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

Created on 12 Oct 2017  Â·  65Comments  Â·  Source: facebook/react-native

Is this a bug report?

yes
screenshot_2017-10-12-14-03-09-58
App.js.txt
User_List.php.txt

Have you read the Contributing Guidelines?

(Write your answer here.)

Environment

Steps to Reproduce

(Write your steps here:)

1.
2.
3.

Expected Behavior

(Write what you thought would happen.)

Actual Behavior

(Write what happened. Add screenshots!)

Reproducible Demo

(Paste the link to an example project and exact instructions to reproduce the issue.)

Ran Commands Locked

Most helpful comment

Hi smithaitufe,
You are having the issue because you are probably exporting addNewTask as default and you importing it as named export.
So change import {addNewTask} from '../actions'; to import addNewTask from '../actions';

All 65 comments

While this report is minimalistic (so I do understand nobody responded on this one), I do have the same error. I'm not on my workspace so I'll try to explain what happens.

I was using version 0.43.x when I upgraded to 0.49.x. This was the moment my app failed because of dependencies (PropTypes, et cetera), so I tried to reinstall packages with NPM, clear cache, et cetera. The code does NOT recognize components by React Native. PHPStorm does not link the imported component (like it should do), so that seems to be related to this error when running run-android.

At this moment I am planning to start a new project (newest version of RN) and copy my src folder into it. But this should not be the right solution huh ;)

Any updates on this?
I'm facing the same error.
I've updated from 0.48.1 to 0.48.4.

I answer my own question.
The fix is fairly simple.
Open App.js file and modify this line
class YourApp extends Component {
into
export default class YourApp extends Component<{}> {

@simoarpe My editor gives me a warning when using <{}>. This seems to be invalid. Is that right?

@bobmulder supposedly it should be accurate, that is the same syntax used in the App.js when a new project is generated using react-native init YourApp.

Okay I'll check it out when I'm home. Thanks for noticing!

Adding export default solved my problem

my code

//Import library to help create component
import React from 'react';
import { AppRegistry } from 'react-native';
import Header from './src/components/header';

//Create a Component
const App = () => (
  <Header />
);

//Export App - This line solved my issue
export default App;

//Render it to the device
AppRegistry.registerComponent('albums', () => App);
//albums is project name that we use while creating RN App

I am facing the same issue on Linux .
react-native-cli: 2.0.1
react-native: 0.50.3
node -v : v9.2.0
npm -v : 5.5.1

I am facing this issue as well. I have tried solutions suggested by @dexter21r and @simoarpe but no luck. I am getting this error not in my root App.js but in one of my screens where i am using a ScrollView

adding export default App worked for me
`//Render it to the device

export default App;

AppRegistry.registerComponent('albums', () => App);`

I was having the same in root App.js

@rakeshgithub answer is work for me

import React, { Component } from 'react';
import { AppRegistry, FlatList,
StyleSheet, Text, View, Image, Alert, Platform,
TouchableHighLight,
RefreshControl, TextInput} from 'react-native';
import {addNewTask} from '../actions';

export default class AddComponent extends Component{
constructor(props)
{
super(props);
this.state = ({
newTaskName: ''
});
}
render(){
return(
backgroundColor: 'tomato',
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'center',
height: 64
}}>
height :40,
width: 200,
margin: 10,
padding: 10,
borderColor: 'white',
borderWidth: 1,
color: 'white'
}}
keyboardType= 'default'
placeholderTextColor= 'white'
placeholder= 'Enter task name'
autoCapitalize= 'none'
onChangeText={
(text) => {
this.setState({
newTaskName: text
});
}
}
/>
style={{
marginRight: 30
}}
underlayColor='blue'
onPress={(event)=>{
if(!this.state.newTaskName.trim()){
return;
}
this.props.onClickAdd(this.state.newTaskName);
//call click event => use "Container"
}}
>
style={{ width: 35, height: 35 }}
source={require('../images/download.png')}
/>


);
}
}

screenshot_1518759528

Please what is the solution to this error? I have tried all the suggestions and no one worked for me.

This is making react native really really unpredictable

Thanks for posting this! It looks like you may not be using the latest version of React Native, v0.53.0, released on January 2018. Can you make sure this issue can still be reproduced in the latest version?

I am going to close this, but please feel free to open a new issue if you are able to confirm that this is still a problem in v0.53.0 or newer.

How to Contribute • What to Expect from Maintainers

Hi smithaitufe,
You are having the issue because you are probably exporting addNewTask as default and you importing it as named export.
So change import {addNewTask} from '../actions'; to import addNewTask from '../actions';

for me it was a difference between:

import App from './app'

and

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

(the latter fixed the issue)

i solve this problem by creating index.js file and exporting the file from it and at app.js import file from index.js .
suppose you have to import loginform.js from ./src/component to app.js then first make index.js file on component folder then export loginform to index.js on app.js import loginform from index.js

having the same problem today and I solved it just as prabin12 did. I created index.js in my components folder and export my app.js from it.

import App from './App.js';
export { App };

The next string version working as expected:

export default class App extends React.Component {

Tive esse problema quando tentei identar o return do render com o parentese na linha debaixo ex:
render() {
return
(
alguma coisa
)
ele só aceitou com o:
return (
alguma coisa
)

I fixed this error after finding that i have been importing Image from native-base isntead of importing it from react-native.

***update*****
I updated RN and React to the latest version, and found other library I have used didn't updated
So I just updated them all, it works now

I got the same issue here. And tried various approaches, still not working. The most awkward thing is I import FormInputUI.js to another file use exactly same way as following and it works in that file.

react-native: 0.55.0,
node: v8.11.1,
npm: 5.6.0

FormInputUI.js

import React from 'react';
import { StyleSheet } from 'react-native';
import { Input, Button } from 'react-native-elements';
import Icon from 'react-native-vector-icons/SimpleLineIcons';

const FormInput = props => {
    const { icon, refInput, ...otherProps } = props
    return (
      <Input
        {...otherProps}
        ref={refInput}
        containerStyle={styles.inputContainer}
        icon={<Icon name={icon} color="#7384B4" size={18} />}
        inputStyle={styles.inputStyle}
        autoFocus={false}
        autoCapitalize="none"
        keyboardAppearance="dark"
        errorStyle={styles.errorInputStyle}
        autoCorrect={false}
        blurOnSubmit={false}
        placeholderTextColor="#7384B4"
      />
    )
}
export default FormInput;

Main.js

import FormInput from './UI/FormInputUI.js';

class LoginForm extends Component {
  render() {
    const {
      isLoading,
      selectedType,
      emailValid,
      passwordValid,
    } = this.state

    return (
      <ScrollView
            scrollEnabled={false}
          keyboardShouldPersistTaps="handled"
          contentContainerStyle={styles.container}
        >
          <KeyboardAvoidingView
            behavior="position"
            contentContainerStyle={styles.formContainer}
          >
            <View>
              <FormInput
                refInput={input => (this.emailInput = input)}
                value={this.props.email}
                onChangeText={this.onEmailChange.bind(this)}
                placeholder="Email"
                keyboardType="email-address"
                returnKeyType="next"
                displayError={!emailValid}
                errorMessage="Please enter a valid email address"
                onSubmitEditing={() => {
                  this.validateEmail()
                  this.passwordInput.focus()
                }}
              />
              <FormInput
                refInput={input => (this.passwordInput = input)}
                value={this.props.password}
                onChangeText={this.onPasswordChange.bind(this)}
                placeholder="Password"
                secureTextEntry
                returnKeyType="next"
                displayError={!passwordValid}
                errorMessage="Please enter at least 6 characters"
                onSubmitEditing={() => {
                  this.validatePassword()
                }}
              />
              { this.renderError() }
            </View>
          </KeyboardAvoidingView>
        </ScrollView>
    )
  }
}

img_6171

Am facing same issue can anyone please help me how to resolve this error
screen shot 2018-05-10 at 5 03 05 pm

@Sunnysh123 Hi did you check your package.json to update some libraries? cause my issue is the version conflict between different libraries and React Native.

@simoarpe Thank you! That fixed it but the code I used is slightly different that what you used:
export default class App extends React.Component {

I solved the issue by importing 'Image' from 'react-native' instead of 'native-base'

You may importing this way:

import { foo } from 'bar'

when you should:

import foo from 'bar'

Double check your imports and exports

I'm also currently having this issue, but the weird part is it happens even when all I call is this:
AppRegistry.registerComponent("AppName", () => <View />);

It's not an export/import issue since all it is is a View. It was running just fine moments ago, I changed nothing and now it won't run. I can run other projects just fine, and I'd really hate to have to push everything to anew project.
Any ideas?

Figured it out, apparently since I had my folder that I keep all of my components and such in called app, when I import App from './app' expecting it to auto pickup the index.js in the root of the folder, it didn't for some reason. But if I rename the folder to src, it works perfectly. My fix was just adding index.js to the end of my import.

I have the same problem tried everything,

Does anyone know how to solve it

 import React, { Component } from 'react';
 import { View } from 'react-native';
//import firebase from 'firebase';
import { Header } from './components/common';
import { LoginForm } from './components/LoginForm';

class App extends Component {
     componentWillMount() {
     }
  render() {
       return (
        <View>
            <Header headerText="Auth" />
           <LoginForm />
     </View>
    );
   }
   }

    export default App;

Did you leave out your render function for privacy reasons or is it empty? I believe it will error out if the return is empty, mine actually won't even build if it's empty. Just trying to cover all the bases.

Problem with native-base component Drawer

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, or you might have mixed up default and named imports.
Check your code at App.js:21.
07-19 18:13:38.381 5975 6003 W ReactNativeJS: in App (at renderApplication.js:33)
07-19 18:13:38.381 5975 6003 W ReactNativeJS: in RCTView (at View.js:60)
07-19 18:13:38.381 5975 6003 W ReactNativeJS: in View (at AppContainer.js:102)
07-19 18:13:38.381 5975 6003 W ReactNativeJS: in RCTView (at View.js:60)
07-19 18:13:38.381 5975 6003 W ReactNativeJS: in View (at AppContainer.js:122)
07-19 18:13:38.381 5975 6003 W ReactNativeJS: in AppContainer (at renderApplication.js:32)

import React, { Component } from 'react';
import {
Text,
} from 'react-native';
import { Drawer, Icon, Button, Container, Header, Content, Left, Right, Body } from 'native-base';
import SideBar from './HomeScreen';

export default class App extends Component {

closeDrawer(){
this._drawer._root.close()
};
openDrawer(){
this._drawer._root.open()
};

render() {
return (
ref = { (ref) => { this._drawer = ref; } }
content = { }
onClose = { () => this.closeDrawer() } >






Home Screen






Home Screen



);
}
}

@ajaykumarramani i have the same problem after updating to latest version of nativebase.

@ajaykumarramani i have the same issue when use native-base component Drawer.

render() {

return (

    <Drawer
    ref={(ref) => { this.drawer = ref; }}
    content={<SideBar {...this.props}/>}
    >
        <View style={styles.container}>
             <Header left='menu' openDrawer={()=>{this.drawer._root.open();}} title={'abc'}/>
             <Content>
                  <View style={{flex: 3, backgroundColor:'blue'}} >
                   </View>         
              </Content>
        </View>
    </Drawer>
);

}

"react-native": "0.56.0",
"native-base": "^2.7.1",

i found the solution by downgrade [email protected]

huh, it was a typo after all. if any of you is getting undefined and check render method of 'xxxxxx' then check the xxxxx module for a typo in the import statement.

@danielland85 same problem, same solution. for anyone else who recently upgraded native-base, they decided to remove the drawer in 2.7.2. SEMVER FTW

If you are importing a class that you have Exported as default. e.g
'export default ClassName';

Then you will get this error.
So instead of importing like this import { ClassName } from './ClassName'

Use

import ClassName from './ClassName'

Hi all,

I have the same problem. I tried all of your solutions but downgrading React from 16.4.2 to 16.2.0 only solve my issue.

Just make sure that your imports are in needed order, I had the same problem and after fix with imports all started to work good.

è¿™

In my case it happened when I was importing List from react-native-elements to use it with FlatList.

However, it seems react-native-elements no longer has List as a component since 1.0.0BETA4. Changing List to View fixed it for me.

I solve it by change

export default App;

to

module.exports = App;

import React, {Component} from 'react';
import {Text, View, TouchableOpacity, Image, TextInput} from 'react-native';
import styles from '../styles/search-web-screen-styles.js';
import LinearGradient from 'react-native-linear-gradient';
import {Surface} from 'gl-react-native';
import { Blur } from "gl-react-blur";

const GL = require("gl-react");

const shaders = GL.Shaders.create(
{
textOverImage: {
frag:`
precision highp float;
varying vec2 uv;

uniform sampler2D img;
uniform sampler2D imgBlurred;
uniform sampler2D txt;

const vec2 shadowCenter = vec2(0.5, 0.9);
const vec2 shadowSize = vec2(0.6, 0.2);
float shadow () {
return 0.8 * smoothstep(1.0, 0.2, distance(uv / shadowSize, shadowCenter / shadowSize));
}
float monochrome (vec3 c) {
return 0.2125 * c.r + 0.7154 * c.g + 0.0721 * c.b;
}
vec3 textColor (vec3 bg) {
return vec3(step(monochrome(bg), 0.6));
}

void main () {
vec4 bg = mix(texture2D(img, uv), texture2D(imgBlurred, uv), shadow());
vec4 fg = vec4(textColor(texture2D(imgBlurred, shadowCenter).rgb), 1.0);
float fgFactor = 1.0 - texture2D(txt, uv).r;
gl_FragColor = mix(bg, fg, fgFactor);
}`
}
}
);

class HelloBlue extends React.Component
{
render()
{
const { img , width, height } = this.props;
return
{img}


{img}





;
}
}

export default class WebSearchScreen extends Component
{
render()
{
return(
onPress = {() => this.props.navigation.goBack()}>


      <View style={styles.view_bottom_bg}>
            <LinearGradient start={{x: 1.0, y: 0.5}} end={{x: 0.5, y: 1.0}}
                            locations={[0.1,0.4,1.0]}
                            colors={['#66c6ff', '#68e3ff', '#ed89ff']}
                            style={styles.LinearGradientStyle} >
                <TextInput
                    placeholder="Tap to type..."
                    placeholderTextColor="#dbdbdb"
                    underlineColorAndroid='transparent'
                    style={styles.TextInputStyleClass}/>
            </LinearGradient>
      </View>

      <Surface style={styles.view_center_bg}>
          <HelloBlue img={"https://i.imgur.com/wxqlQkh.jpg"} />
      </Surface>


  </View>
)

}
}

I am getting the same error in this class . please help me to solve this , I am not getting any link or solution of it.

It's import problem. When I used:
in cart.js
const CartItem = require("./cart-item");
in cart-item.js
export default CartItem
I did have this problem, but when I change import:
in cart.js
import CartItem from "../cart/cart-item";
all works fine!

TL;DR
You should use import Module from '...' & export default Module pair.
And const Module = require(...) is same with import * as Module from '...'.


It's not matter of react native. It's matter of javascript importing mechanism (esm, commonjs)
Simple solution is to check how to importing React library. Please follow one of below two instruction types.

I think it will help.

1. Synthetic import

import * as React from 'react'

// -> should import module with `* as`
import * as Module from 'third-party-module'

// In this case, it's also works.
// but it's not good to use `import` and `require` together
const Module = require('third-party-module')

2. Not synthetic import

import React from 'react'

// -> should import default
import Module from 'third-party-module'

If you are importing a class that you have Exported as default. e.g
'export default ClassName';

Then you will get this error.
So instead of importing like this import { ClassName } from './ClassName'

Use

import ClassName from './ClassName'

This solved it for me

A slight variation that I'm including for any others that also hit it.

For me, the this code was causing that same error.
This fails:

    import { View, Text } from 'react-native-elements';

    return (
      <View>
        <Text style={{color: 'red'}}>
          and red
        </Text>
      </View>
    );

(although bizarrely, if I changed the View to a Text it worked)

The fix for me was to import from react-native not from react-native-elements.

This works :

  import { View, Text } from 'react-native';

    return (
      <View>
        <Text style={{color: 'red'}}>
          and red
        </Text>
      </View>
    );

i have been having the same error, i tried all the above solutions and even went to just making a very simple app and discovered that the error only popped up when i was setting up my redux, when i added //// <Provider store={store}>
<TodoApp />
<Provider>

the problem might be due to the latest redux package but then again i m not to experienced in react-native to give a solid conclusion.

please assist me further on my issue

my mistake!!! i was importing my Provider from 'redux' instead from 'react-redux' once i fixed that issue the error stopped showing up
import { Provider } from 'redux' // WRONG!!
i corrected the imports by:
import { Provider } from 'react-redux' //CORRECT!!

after i fixed that the error stopped showing up!

happy coding people!

Removing the curly braces from the name of the function or the class, which I am importing solved the error for me.
Like-
import NewHeader from './components/Header.js';
instead of
import {NewHeader} from './components/Header.js';

My reason of getting this error was that I've forgotten to add arguments section for function expression.
It was

const Comp = (
    <View style={{ justifyContent: 'space-between', flexDirection: 'row' }}/>
);

Instead of

const Comp = () => (
    <View style={{ justifyContent: 'space-between', flexDirection: 'row' }}/>
);

Then Comp was rendered as child of other component.
Hope this helps.

I am facing the same issue on Linux .
react-native-cli: 2.0.1
react-native: 0.50.3
node -v : v9.2.0
npm -v : 5.5.1

I'm having the same issue, and it's the same react-native version. Renaming with "export default" or importing correctly is not the problem. Any news? If I update it, it should work?

I get this issue as well. And I replace the TouchableOpacity import source 'from "native-base";' with 'from "react-native";'.it's work for me

I narrowed down my error to navigationOptions.

          ` static navigationOptions = ({ navigation }) => ({
    headerRight: typeof (navigation.state.params) === 'undefined' || typeof (navigation.state.params.headerRig) === 'undefined' ?
        <Icon name="camera" size={25} color='#000000' style={{ padding: 10 }} onPress={() => { navigation.navigate('ImagePost') }} /> : navigation.state.params.headerRig,

    headerLeft: (<Text style={{ padding: 10, fontSize: 16, color: '#000000' }}>Gallery</Text>),
});`

how can i fix this??

in file index.js the first i wrote like that:
AppRegistry.registerComponent(appName, () =>);
then i got the same error like above so i have changed it into
=>AppRegistry.registerComponent(appName, () =>App);

I fixed this error after finding that i have been importing Image from native-base isntead of importing it from react-native.

Thanks. This helped me

The same issue. I'm trying to pass redux store from first index.js to the next Components. The problem is when I'm passing the store to a simple Component, it's all right, but when I try to pass the store to decorated component, which is being exported like this:
export default connect( mapToStateProps, mapDispatchToProps )(Component);
then I get this error. I can't understand why is this happening. Is this because of "complex" store prop that shouldn't be passed to decorated Components?

In my case it was a lack of attention, without realizing it was importing a class from a file that it did not exist. It was importing along with other classes from this same file, and only then did I realize that specifically this class was not from such a file.
My suggestion, check 100% imports if it's right, it might be a simple mistake.

This isn't the most helpful error message. my issue was in the import

import Provider from 'react-redux';

instead of

import { Provider } from 'react-redux';

When you "export default" something then in your imports you can name it anything you want and you don't need to use curly braces around the import for example:

Export: export default class A
Then Import Like: import AnyNameYouWant from 'filepath'

But if you are exporting the class A like this:

Export: export class A
Then Import Like: import { A } from 'filepath' // name must be the same as exported name

If you have a lot of exports from a single file e.g:

export class A
export class B

Then you can import them like:

import * as myClasses from 'filepath';
To access class A: myClasses.A
To access class B: myClasses.B

I was getting this error when I was not putting curly braces around my imports when they were not being exported as default

damn, @igorchru was right. It's all about attention. you see, i got same problem, turn out I was importing Card component from 'react-native' instead 'react-native-elements'. And my problem is solved.

pay attention to your code guys, stay sharp

some kind of whitespace that was not the standard white space was left by code I copied from the internet. I removed everything between component tags and it started working.

Was this page helpful?
0 / 5 - 0 ratings