How to set default font family in 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.
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
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.
For React Native 0.56.0+ check if defaultProps is defined first:
Text.defaultProps = Text.defaultProps || {}
Then add:
Text.defaultProps.style = { fontFamily: 'some_font' }
Add the above in the constructor of the App.js file (or any root component you have).
In order to override the style you can create a style object and spread it then add your additional style
(e.g { ...baseStyle, fontSize: 16 }
)
You can override Text behaviour by adding this in any of your component using Text:
let oldRender = Text.prototype.render;
Text.prototype.render = function (...args) {
let origin = oldRender.call(this, ...args);
return React.cloneElement(origin, {
style: [{color: 'red', fontFamily: 'Arial'}, origin.props.style]
});
};
Edit: since React Native 0.56, Text.prototype
is not working anymore. You need to remove the .prototype
:
let oldRender = Text.render;
Text.render = function (...args) {
let origin = oldRender.call(this, ...args);
return React.cloneElement(origin, {
style: [{color: 'red', fontFamily: 'Arial'}, origin.props.style]
});
};
With React-Native 0.56, the above method of changing Text.prototype.render
does not work anymore, so you have to use your own component, which can be done in one line!
MyText.js
export default props => <Text {...props} style={[{fontFamily: 'Helvetica'}, props.style]}>{props.children}</Text>
AnotherComponent.js
import Text from './MyText';
...
<Text>This will show in default font.</Text>
...