facebook / react-native

A framework for building native applications using React
https://reactnative.dev
MIT License
119.31k stars 24.35k forks source link

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 closed 6 years ago

AAGSICON commented 7 years ago

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

bobmulder commented 7 years ago

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 commented 7 years ago

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

simoarpe commented 7 years ago

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 commented 7 years ago

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

simoarpe commented 7 years ago

@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 commented 7 years ago

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

dexter21r commented 7 years ago

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 commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

@rakeshgithub answer is work for me

Johncy1997 commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

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

Guy-Leumi commented 6 years ago

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 commented 6 years ago

for me it was a difference between:

import App from './app'

and

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

(the latter fixed the issue)

prabin12 commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

The next string version working as expected:

export default class App extends React.Component {

thiago-molive commented 6 years ago

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 commented 6 years ago

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

kmtilwani commented 6 years ago

Help Me with this --- https://stackoverflow.com/questions/49892807/react-native-camera-video-capturing-shows-error-on-preview-after-it-gets-capture

129emma commented 6 years ago

**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 commented 6 years ago

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 commented 6 years ago

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

pazcur commented 6 years ago

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

jamils82 commented 6 years ago

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

phsantiago commented 6 years ago

You may importing this way:

import { foo } from 'bar'

when you should:

import foo from 'bar'

Double check your imports and exports

0paIescent commented 6 years ago

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?

0paIescent commented 6 years ago

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.

bavly commented 6 years ago

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;
0paIescent commented 6 years ago

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.

ajaykumarramani commented 6 years ago

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 ( <Drawer ref = { (ref) => { this._drawer = ref; } } content = { <SideBar navigator={ this._navigator } /> } onClose = { () => this.closeDrawer() } >

Home Screen
Home Screen
 </Drawer>
);

} }

r3wt commented 6 years ago

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

danielland85 commented 6 years ago

@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",

danielland85 commented 6 years ago

i found the solution by downgrade native-base@2.7.0

izkshitiz commented 6 years ago

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.

r3wt commented 6 years ago

@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

Lalee10 commented 6 years ago

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'

thomasphilibert commented 6 years ago

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.

AlexanderSutul commented 6 years ago

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.

magicismight commented 6 years ago

ghost commented 6 years ago

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 commented 6 years ago

I solve it by change

export default App;

to

module.exports = App;
iqbinder commented 6 years ago

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} Hello world ; } } export default class WebSearchScreen extends Component { render() { return( this.props.navigation.goBack()}> ) } } 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 commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

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