3

I import a color as props.color into my functional component 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;
TylerH
  • 20,799
  • 66
  • 75
  • 101
Matt Laszcz
  • 373
  • 3
  • 20

2 Answers2

6

Well, of course it doesn't recognize tagColor, it's in a different scope. Notice tagColor is in the scope of your function component, 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.

Ron B.
  • 1,502
  • 2
  • 7
1

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'>