Sydney
Sydney

Reputation: 1439

Reactnative error - expected a string or a class/function but got: undefined

I am hitting this error when i am trying to define my own custom components.

// /common/MyAppText.js
import React, {Component} from 'react';
import {
  Text,
  View,
} from 'ReactNative';

class MyAppText extends Component {
  render(){
    return (
      <View>
        <Text>hello</Text>
      </View>
    )
  }
}

export default MyAppText

On the other app, i tried to import it and use it by

import MyAppText from './common/MyAppText'
class Home extends Component {
  render(){
    return (
      <View>
        <MyAppText />
      </View>
    )
  }
}

But i hit the error "expected a string or a class/function but got: undefined, please check render method of 'MyAppText'. Anyone can see what is wrong with the export syntax?

If i defined everything in the same document then it works, so it is something with the export that i couldn't figure out.

Upvotes: 1

Views: 695

Answers (1)

jevakallio
jevakallio

Reputation: 35970

Your own export/import looks fine. Not sure if this is the issue, but the line

import {..} from 'ReactNative';

Should be:

import {..} from 'react-native';

You might expect that to crash with a different error (module not found), but since this internal React Native file exports a globally available module "ReactNative" via Haste, your import ends up picking that file. Because that file doesn't export properties View and Text, the code compiles fine, but ends up with undefined variables.

Edit for more context:

The React Native bundler (called Metro) uses Facebook's own module system (called Haste), which allows anybody to decorate a file with a comment @providesModule Name, and then import it from globally anywhere with just import ... from 'Name';

One of the internal renderer modules declares @providesModule ReactNative. So when you've imported from 'ReactNative', you got that module instead of a build error.

Upvotes: 4

Related Questions