I am learning react native and wanted to use a variable in my styles to keep things dry. I created a constant that looks like this:
export default {
primary: 'black',
accent: 'white'
}
then I imported it and where I use it directly in a color prop on a component it works just fine:
<View style={button}><Button title='reset' color={primary}/></View>
however when I try to use it in StyleSheets I get this error: "Uncaught Error Can't find variable: primary"
here is my component:
import React from 'react'
import colors from '../constants/colors'
import { View, Text, StyleSheet } from 'react-native'
const Header = () => {
const { header, headerTitle} = styles
const { primary } = colors
return (
<View style={header}>
<Text style={headerTitle}>Guess a Number</Text>
</View>
)
}
const styles = StyleSheet.create({
header: {
width: '100%',
height: 90,
paddingTop: 36,
backgroundColor: primary,
alignItems: 'center',
justifyContent: 'center'
},
headerTitle : {
color: 'white',
fontSize: 18
}
})
export default Header
I did triple check to make sure the path to colors is correct.
CodePudding user response:
The solution ended up being that I had used destructuring in this component and the StyleSheet is outside the component scope. So I have to either destructure outside the component or use the long hand syntax colors.primary.
CodePudding user response:
This should go into comments but here I am lacking the reputation points to comment and for a reason so, but let me try to help:
Have you tried to declare a variable for your values first?
const myColors = {
primary: 'black',
accent: 'white'
}
export default myColors