Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default font family in React Native?

Tags:

react-native

Is there an equivalent to this CSS in React Native, so that the app uses the same font everywhere ?

body {
  font-family: 'Open Sans';
}

Applying it manually on every Text node seems overly complicated.

like image 544
Dagobert Renouf Avatar asked Oct 09 '22 01:10

Dagobert Renouf


People also ask

How do I change the default font size in react?

To set a global font family in React, set the font-family style on the html element in your index. css file and import the file in your index. js file. Global CSS should be imported in index.


2 Answers

The recommended way is to create your own component, such as MyAppText. MyAppText would be a simple component that renders a Text component using your universal style and can pass through other props, etc.

https://reactnative.dev/docs/text#limited-style-inheritance

like image 92
David E. Chen Avatar answered Oct 16 '22 09:10

David E. Chen


There was recently a node module that was made that solves this problem so you don't have to create another component.

https://github.com/Ajackster/react-native-global-props

https://www.npmjs.com/package/react-native-global-props

The documentation states that in your highest order component, import the setCustomText function like so.

import { setCustomText } from 'react-native-global-props';

Then, create the custom styling/props you want for the react-native Text component. In your case, you'd like fontFamily to work on every Text component.

const customTextProps = { 
  style: { 
    fontFamily: yourFont
  }
}

Call the setCustomText function and pass your props/styles into the function.

setCustomText(customTextProps);

And then all react-native Text components will have your declared fontFamily along with any other props/styles you provide.

like image 71
Ajackster Avatar answered Oct 16 '22 11:10

Ajackster