Search code examples
csstextviewreact-nativestyles

How can I make all the Text children of a View element have the same style?


I want to have something similar to CSS, where you can give the 'color' style to a div and any text within it will have it.

I have multiple Text components within a View component and I would like them to all have the same text color.

If I pass a 'color' style to the view it would throw a warning.

I would like to avoid having to pass the same style to all these children when their parent can have the style for all of them.

I would like to go from this:

<View>
  <Text style={styles.Warning}>
  </Text>
  <Text style={styles.Warning}>
  </Text>
  <Text style={styles.Warning}>
  </Text>
  <Text style={styles.Warning}>
  </Text>
  <Text style={styles.Warning}>
  </Text>
</View>

to this:

<View style={styles.Warning}>
  <Text>
  </Text>
  <Text>
  </Text>
  <Text>
  </Text>
  <Text>
  </Text>
  <Text>
  </Text>
</View>

With the styles being:

const styles = StyleSheet.create({
  Warning:{
    color:'#a94442'
  }
});

(It would be better if I don't have to install anything) Thank you.


Solution

  • Yes, you can definitely do the same you want. The only part you are missing is having the Text container inside he View container.

    Example:

    <View>
     <Text style={{color:'red'}}>
       <Text>
         text1 // will inherit red color
       </Text>
       <Text>
         text2 // will inherit red color
       </Text>
     </Text>
    </View>
    

    For further information you can also check out the link https://facebook.github.io/react-native/docs/text.html#containers