Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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. #16332

Closed
AAGSICON opened this issue Oct 12, 2017 · 65 comments
Labels
Ran Commands One of our bots successfully processed a command. Resolution: Locked This issue was locked by the bot.

Comments

@AAGSICON
Copy link

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:)

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

@bobmulder
Copy link

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 ;)

@simoarpe
Copy link

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

@simoarpe
Copy link

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<{}> {

@bobmulder
Copy link

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

@simoarpe
Copy link

simoarpe commented Oct 17, 2017

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

@bobmulder
Copy link

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

@dexter21r
Copy link

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

@jayeshjain24
Copy link

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

@HannanShaik
Copy link

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

@rakeshgithub
Copy link

rakeshgithub commented Dec 21, 2017

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

@satejsarker
Copy link

@rakeshgithub answer is work for me

@Johncy1997
Copy link

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(
<View style={{
backgroundColor: 'tomato',
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'center',
height: 64
}}>
<TextInput style={{
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
});
}
}
/>
<TouchableHighLight
style={{
marginRight: 30
}}
underlayColor='blue'
onPress={(event)=>{
if(!this.state.newTaskName.trim()){
return;
}
this.props.onClickAdd(this.state.newTaskName);
//call click event => use "Container"
}}
>
<Image
style={{ width: 35, height: 35 }}
source={require('../images/download.png')}
/>


);
}
}

screenshot_1518759528

@smithaitufe
Copy link

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

@react-native-bot
Copy link
Collaborator

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 ContributeWhat to Expect from Maintainers

@react-native-bot react-native-bot added Ran Commands One of our bots successfully processed a command. Stale There has been a lack of activity on this issue and it may be closed soon. labels Feb 24, 2018
@stale stale bot removed the Stale There has been a lack of activity on this issue and it may be closed soon. label Feb 24, 2018
@Guy-Leumi
Copy link

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';

@olegdater
Copy link

for me it was a difference between:

import App from './app'

and

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

(the latter fixed the issue)

@prabin12
Copy link

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

@terada46
Copy link

terada46 commented Mar 17, 2018

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 };

@Kotdnz
Copy link

Kotdnz commented Mar 19, 2018

The next string version working as expected:

export default class App extends React.Component {

@thiago-molive
Copy link

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
)

@darula-hpp
Copy link

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

@129emma
Copy link

129emma commented May 5, 2018

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

@SaikrishnaM230
Copy link

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

@129emma
Copy link

129emma commented May 10, 2018

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

@magicismight
Copy link
Contributor

@ghost
Copy link

ghost commented Aug 30, 2018

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.

@CatherineLiyuankun
Copy link

I solve it by change

export default App;

to

module.exports = App;

@iqbinder
Copy link

iqbinder commented Sep 8, 2018

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 <GL.Node shader={shaders.textOverImage}>
<GL.Uniform name="img">
{img}
</GL.Uniform>
<GL.Uniform name="imgBlurred">

{img}

</GL.Uniform>
<GL.Uniform name="txt">
Hello world
</GL.Uniform>
</GL.Node>;
}
}

export default class WebSearchScreen extends Component
{
render()
{
return(


<TouchableOpacity style={styles.cross_btn_bg}
onPress = {() => this.props.navigation.goBack()}>
<Image source={require('../assets/icons/cross_1x.png')} />

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

@kibernetika
Copy link

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!

@vreality64
Copy link
Contributor

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'

@edemagbenyo
Copy link

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

@krisrandall
Copy link

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>
    );

@EphraimMwanda
Copy link

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

@EphraimMwanda
Copy link

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!

@notKvS
Copy link

notKvS commented Oct 16, 2018

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';

@alexeykomov
Copy link

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.

@paulopacitti
Copy link

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?

@mpp21x
Copy link

mpp21x commented Nov 5, 2018

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

@jeffreyongcay
Copy link

@mopilo
Copy link

mopilo commented Dec 13, 2018

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??

@SORNVENGE
Copy link

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);

@thevikasthakur
Copy link

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

@TimmyGOGO
Copy link

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?

@igorchru
Copy link

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.

@nickhalldev
Copy link

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';

@Lalee10
Copy link

Lalee10 commented Jan 31, 2019

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

@fadilnatakusumah
Copy link

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

@phoenixxd
Copy link

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.

@facebook facebook locked as resolved and limited conversation to collaborators Feb 25, 2019
@react-native-bot react-native-bot added the Resolution: Locked This issue was locked by the bot. label Feb 25, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Ran Commands One of our bots successfully processed a command. Resolution: Locked This issue was locked by the bot.
Projects
None yet
Development

No branches or pull requests