Search code examples
javascriptreact-nativedestructuring

Unsuccessfully destructuring the object inside the function


I have a js file name index.js inside a folder utils

Inside the file:

export const colors = {
  PRIMARY_COLOR: "#ff304f",
  SECONDARY_COLOR: "#002651",
  BORDER_COLOR: "#dbdbdb",
};

I try to destructuring it inside my WeatherInfo component like this:

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

import { colors } from "../utils";

export default function WeatherInfo({ currentWeather }) {

  const { PRIMARY_COLOR } = colors;
  // console.log(colors);

  return (
    <View>
      <Text style={styles.textPrimary}>{temp}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  textPrimary: {
    fontSize: 40,
    color: PRIMARY_COLOR,
  },
});

I got error of saying Can't find variable: PRIMARY_COLOR, however if I console.log(colors) inside the function, I can see the object printed in the expo console. However, if I do it outside the function, it works. Can someone explain to me what happened?


Solution

  • You are doing it right, but you just misplaced your code it should be outside from function body that's how it will be available on the whole page

    const { PRIMARY_COLOR } = colors;
    

    Move it up just one line.