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

2

8

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.

Filberto answered 29/3, 2017 at 0:16 Comment(0)
F
4

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

Flirtatious answered 29/3, 2017 at 5:0 Comment(1)
But that's not the layout the OP wanted? You are now nesting Text elements inside Text elements.Marcy
I
2

You can't. Color is just another font style, this limitation is decribed in the documentation

You also lose the ability to set up a default font for an entire subtree. Meanwhile, fontFamily only accepts a single font name, which is different from font-family in CSS. The recommended way to use consistent fonts and sizes across your application is to create a component MyAppText

So basically it says, wrap Text in something like "StyledText" and use that instead. So you should build a style library for all styles you want to use. As an example for a LightBold text:

import { StyleSheet, Text } from "react-native";

const styles = StyleSheet.create({
  fontLight: {
    color: '#fff',
    fontWeight: 'bold'
  }
};

function LightBoldText({children}) {
  return <Text style={styles.fontLight}>{children}</Text>
}

// then you'll use it as any component
function MyComponent() {
  return <LightBoldText>Some Text</LightBoldText>
}
Insatiate answered 14/8, 2023 at 15:27 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.