Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of !important in React Native

I have Text component inside another Text component:

<Text style = {styles.firstText}>
     {this.props.firstText}

     {'  '}

     <Text style = {styles.secondText}>
           second text
     </Text>

     {'  '}

     <Text style = {styles.thirdText}>
           {this.props.thirdText}
     </Text>
</Text>

FirstText has fontFamily = X.

SecondText needs to have fontFamily = Y but X applies also here.

How can I set a priority here?

Have tried with fontFamily: 'Y' + ' !important' but no luck.

like image 585
Ivan Burzakovskiy Avatar asked Dec 06 '25 06:12

Ivan Burzakovskiy


1 Answers

You can read the docs where they say:

The recommended way to use consistent fonts and sizes across your application is to create a component MyAppText that includes them and use this component across your app. You can also use this component to make more specific components like MyAppHeaderText for other kinds of text.

You create a Wrapper for your Text with the style you want:

class MyAppHeaderText extends Component {
  render() {
    return (
      <MyAppText>
        <Text style={{fontSize: 20}}>{this.props.children}</Text>
      </MyAppText>
    );
  }
}

And use it across your app:

<View>
  <MyAppText>
    Text styled with the default font for the entire application
  </MyAppText>
  <MyAppHeaderText>Text styled as a header</MyAppHeaderText>
</View>

They also explain that what is happening to you is on purpose.

React Native still has the concept of style inheritance, but limited to text subtrees. In this case, the second part will be both bold and red.

<Text style={{fontWeight: 'bold'}}>
  I am bold
  <Text style={{color: 'red'}}>and red</Text>
</Text>

And they also explain why:

  • (Developer) React components are designed with strong isolation in mind: You should be able to drop a component anywhere in your application, trusting that as long as the props are the same, it will look and behave the same way. Text properties that could inherit from outside of the props would break this isolation.

  • (Implementor) The implementation of React Native is also simplified. We do not need to have a fontFamily field on every single element, and we do not need to potentially traverse the tree up to the root every time we display a text node. The style inheritance is only encoded inside of the native Text component and doesn't leak to other components or the system itself.

like image 89
Vencovsky Avatar answered Dec 08 '25 19:12

Vencovsky