React Native TypeError: undefined is not an object

I got the error while evaluating a const object, here’s a minimal working example:

import React from "react";
import { View, StyleSheet } from "react-native";

const App = () => {
  return (
    <View style={styles.container}></View>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor:colors.bg,
  },
});

const colors = {
  bg:'blue',
}

export default App;

Error message: TypeError: undefined is not an object (evaluating 'colors.bg')

What’s going on here?

Answer

You have to define colors const before the styles.

Try This

import React from 'react';
import {View, StyleSheet} from 'react-native';

const App = () => {
  return <View style={styles.container}></View>;
};

const colors = {
  bg: 'blue',
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: colors.bg,
  },
});

export default App;