I import a color as props.color into my functional ponent and set it as the state 'tagColor'. When I use tagColor as a value in my stylesheet to set the background color i receive the error 'variable tagColor not found'
How can I use variables inside my stylesheet?
const Tag = (props) => {
const [tagColor, setColor] = useState(props.color)
return (
<View style={styles.container}>
<TouchableOpacity style={styles.tag} title='tag'>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
alignItems: "center",
justifyContent: "center",
height: 25,
display: 'flex'
},
tag: {
backgroundColor: tagColor,
}
});
export default Tag;
I import a color as props.color into my functional ponent and set it as the state 'tagColor'. When I use tagColor as a value in my stylesheet to set the background color i receive the error 'variable tagColor not found'
How can I use variables inside my stylesheet?
const Tag = (props) => {
const [tagColor, setColor] = useState(props.color)
return (
<View style={styles.container}>
<TouchableOpacity style={styles.tag} title='tag'>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
alignItems: "center",
justifyContent: "center",
height: 25,
display: 'flex'
},
tag: {
backgroundColor: tagColor,
}
});
export default Tag;
Share
Improve this question
edited May 23, 2022 at 21:17
TylerH
21.1k77 gold badges79 silver badges112 bronze badges
asked Sep 8, 2021 at 15:52
Matt LaszczMatt Laszcz
4096 silver badges25 bronze badges
2 Answers
Reset to default 8Well, of course it doesn't recognize tagColor
, it's in a different scope. Notice tagColor
is in the scope of your function ponent, while the StyleSheet
is a different scope.
One way to solve this is to directly pass the backgroundColor
to the style
prop, like that:
<TouchableOpacity style={{backgroundColor: tagColor}} title="tag">
Another way is to define the tag
class in your StyleSheet
as a function that receives the color and returns the style, like:
const styles = StyleSheet.create({
container: {
...
},
tag: tagColor => ({
backgroundColor: tagColor,
})
});
And then use it like that:
<TouchableOpacity style={styles.tag(tagColor)} title="tag">
I'd go with the first way if you don't have any more styles other than backgroundColor
. If you need more styles, go with the 2nd method.
If tagColor is the only style you wish to apply you can do this:
<TouchableOpacity style={{ backgroundColor: tagColor }} title='tag'>
If you want to apply tagColor and also apply styles from a style sheet (EG container) you could put both inside an array like this:
<TouchableOpacity style={[styles.container, { backgroundColor: tagColor }]} title='tag'>