Search code examples
javascriptreactjsreact-nativereact-native-stylesheet

Using variables inside react native stylesheets wont recognize the variable


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;

Solution

  • 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.