I am learning react-native
, trying to create some demo apps just for learning. I want to set fontFamily
to roboto thin of my toolbar title.
The best way to do it would be to create your own custom component for Text and import it from another file.
Assuming you want to change the default font to "opensans-semibold" (that is the name I gave it after downloading it and saving it).
TYPESCRIPT:
import React from 'react';
import { Text as DefaultText, StyleSheet } from 'react-native';
export function Text(props : any) {
return(
<DefaultText style={[styles.defaultStyles, props.style]}> {props.children} </DefaultText>
)
}
const styles = StyleSheet.create({
defaultStyles: {
fontFamily: "opensans-semibold"
}
});
Now import this anywhere else as:
import { Text } from './path/to/component'
and use it as you normally would.
@nitin-anand's answer was the most appropriate and cleaner than the rest, but that method is now deprecated and now we will have to create a react-native.config.js
file in our root with the following configuration as an example:
module.exports = {
project: {
ios: {},
android: {},
},
assets: ['./assets/fonts'],
};
For Android :
put your custom fonts in the following folder:
Project folder/android/app/src/main/assets/fonts/font_name.ttf
Run react-native run-android
Use the font i your code:
title: { fontSize: 20, fontFamily: " font Name" },
If you're using React Native chances are that you are using Expo as well. If that's the case, then you can load custom fonts using Expo's Font.loadAsync method.
Steps:
./assets/fonts
directory (if the directory doesn't exist, create it)From the target component (for example: App.js
) load Expo's Font
module:
import { Font } from 'expo'
Load the custom font using componentDidMount:
componentDidMount() {
Font.loadAsync({
'Roboto': require('../assets/fonts/Roboto-Regular.ttf'),
})
}
Finally, use the style
attribute to apply the desired font on a <Text>
component:
<Text style={{fontFamily: 'Roboto', fontSize: 38}}>Wow Such Title</Text>
From the cli docs, "rnpm" is deprecated and support for it will be removed in next major version of the CLI.
Instead, create a react-native.config.js
in your project folder
module.exports = {
assets: ['./assets/fonts'],
};
Put your fonts in ./assets/fonts. Reference your fonts (e.g. McLaren-Regular.ttf) in the styles prop, {fontFamily: 'McLaren-Regular'}
. If you're using styled components, then font-family: McLaren-Regular
No linking or legacy build settings needed for either platforms. If that didn't work (sometimes it doesn't for me), run npx react-native link
, even if you're using autolinking.
Add your fonts file in
Project folder/android/app/src/main/assets/fonts/font_name.ttf
react-native run-android
fontFamily: 'font_name'
Check here for further examples Custom Font Examples