Search code examples
react-nativestylesexporeact-native-web

React Native Web Error: Uncaught ReferenceError: styles is not defined


I'm trying to make a prototype of application with React Native, compatible for WEB browser, and iOS. iOS simulator is rendering without any problem, but the web browser, instead, is giving me error. It happens when using the external file defining the style.

Should there be any difference for linking the external style file with webbrowser and iOS?

When including the style code inside the js file, it works without any problem, but error occurs when trying to make the style codes external file.

Error:

ReferenceError: styles is not defined

Style code(external file)

import { StyleSheet } from 'react-native';

export default styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ddd',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Main js file trying to import style

import React from 'react';
import { Text, View, } from 'react-native';
import styles from '../styles.js'

export default class Profile extends React.Component{

  render(){
    return (
      <View style={styles.container}>
        <Text>Profile</Text>
      </View>
    );
  }
}

Solution

  • I think the problem is with the assignemnt to a variable, try this,

    export default StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#ddd',
        alignItems: 'center',
        justifyContent: 'center',
      },
    });
    

    or may be this,

    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#ddd',
        alignItems: 'center',
        justifyContent: 'center',
      },
    });
    
    export default styles 
    

    Or you can do this,

    export const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#ddd',
        alignItems: 'center',
        justifyContent: 'center',
      },
    });
    

    And then import is as,

    import { styles } from '../styles'  //Make sure the path is correct
    

    Note: I doubt about the file path. Basically main.js file is in src folder and importing a file with path ../ means you are stepping out 1 folder up. If styles.js file is in same folder where you have main.js file, you just need to import like this,

    import { styles } from './styles'  //Here `./` means the same folder.