This is my react-native.config.js file:
module.exports = {
project: {
ios: {},
android: {}, // grouped into "project"
},
assets: ['./assets/fonts/'], // stays the same
};
I added some fonts to my assets/fonts folder and ran react-native link. after this I tested my application on IOs emulator and fonts have worked fine but on android it is not working.
Here is the whole component:
import React from 'react';
import {SafeAreaView, StyleSheet, Text} from 'react-native';
const styles = StyleSheet.create({
textContainer: {
marginTop: '30%',
alignSelf: 'center',
},
text: {
fontFamily: 'BodoniSvtyTwoITCTTBook',
color: 'red',
fontSize: 25,
},
});
const App = () => {
return (
<SafeAreaView style={styles.textContainer}>
<Text style={styles.text}>
Welcome to Font-Play in react-native for android
</Text>
</SafeAreaView>
);
};
export default App;
Location of the assets in android folder:
Any suggestions please?
add fonts in android/app/src/main/assets/fonts in the case of android and re-run the app.
When using lottie in expo and react-native, all animations work on ios however crash the app on android. Is there something special for android I am missing?
I have created a new project and duplicated the issue by coping the code from the docs here
import React from 'react';
import { Button, StyleSheet, View } from 'react-native';
import LottieView from "lottie-react-native";
export default class App extends React.Component {
componentDidMount() {
this.animation.play();
// Or set a specific startFrame and endFrame with:
// this.animation.play(30, 120);
}
resetAnimation = () => {
this.animation.reset();
this.animation.play();
};
render() {
return (
<View style={styles.animationContainer}>
<LottieView
ref={animation => {
this.animation = animation;
}}
style={{
width: 400,
height: 400,
backgroundColor: '#eee',
}}
source={require('./assets/gradientBall.json')}
// OR find more Lottie files # https://lottiefiles.com/featured
// Just click the one you like, place that file in the 'assets' folder to the left, and replace the above 'require' statement
/>
<View style={styles.buttonContainer}>
<Button title="Restart Animation" onPress={this.resetAnimation} />
</View>
</View>
);
}
}
If you are using Expo, you can't use Lottie 3 Files. From the expo api reference (https://docs.expo.io/versions/latest/sdk/lottie/):
"
Known Issues:
The Lottie SDK is currently considered to be under Expo's "DangerZone" because it's implementation is still in Alpha.
Importing Lottie 3 files causes the previewer to crash without a visible error, because Expo relies on lottie-react-native v2.
"
Run Yarn add lottie-react-native#3.0.3 or npm install lottie-react-native#3.0.3
I'm using the example found here & currently facing issue with the toast not showing at all... I just have the initial 'Welcome to React Native!' screen in the emulator. My app structure is as follows:
testApp
android
app
src
main
java
com
testApp
CustomToastPackage.java
MainActivity.java
MainApplication.java
ToastModule.java
res
assets
index.android.bundle
AndroidManifest.xml
ios
node_modules
app.json
App.js
index.js
package.json
ToastExample.js
yarn.lock
My index.js
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import {NativeModules} from 'react-native'; //Added this
module.exports = NativeModules.testApp; //Added this
AppRegistry.registerComponent(appName, () => App);
My App.js
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import ToastExample from './ToastExample'; //Added this
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
android:
'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.instructions}>To get started, edit App.js</Text>
<Text style={styles.instructions}>{instructions}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
As you can see from the file structure I created an additional file named ToastExample.js that contains following based upon the answer found here
import {NativeModules} from 'react-native';
module.exports = NativeModules.ToastExample;
Package name is simply
com.testapp
I can't figure out why the toast never shows? I know react comes with toast support but looking to build upon an initial example to include more advanced Java/Android code...
In your example you didn't add ToastExample in index.js you need to add this into rendering method in index.js like below.
return(
<ToastExample/>
)
In addition to that, you are going to create an android native module which can be used only for android.
But According to my point of view, you can use toast messages module which can be used in both Android and Ios. Otherwise, you need to create ios base native module for creating toast for ios. If u don't want to ios base implementation, it's ok to use this native module. But you block your Ios deployment by it.
I would like to suggest this https://github.com/crazycodeboy/react-native-easy-toast#readme
easy-toast for u. It will work on both Android and IOS devices. You can customize it like android native toast as well. It is easy to implement in your application.
Thanks #Ariel & #Lucefer for feedback, I made the update you suggested but ran into another error. Posting this answer to save anyone potential headache caused by using Android Studio as IDE with React Native. Turns out the MainApplication.java file had 2 items (import of CustomToastPackage & ReactPackage) greyed out & could never figure out why? See the screenshot below
I created a separate application (react-native init newapp) & used a simple text editor (Atom or gedit will do instead of Android Studio) to make the changes & the example runs just fine now.
try this:
<Root>
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.instructions}>To get started, edit App.js</Text>
<Text style={styles.instructions}>{instructions}</Text>
</View>
</Root>
just import Root to react native
I'm able to add normal fonts, but not FontAwesome, i'm using v4.7.0 of FontAwesome.
I've checked older answers on SO, but I only found this one to be relevant, but I think the answer is outdated, because you cant link fonts with the first letter of the file name being lowercase, it has to be uppercase, like 'Font Awesome.ttf' for example(which is what I have right now). This naming strategy worked for adding another regular font called 'Titillium Web'.
My index.js
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.fontawesome}></Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
fontawesome:{
fontFamily: 'Font Awesome',
color: '#000',
fontSize: 20
},
});
AppRegistry.registerComponent('myappname', () => App);
In my package.json
"rnpm": {
"assets": [
"./src/assets/fonts/TitilliumWeb",
"./src/assets/fonts/FontAwesome"
]
},
Executed react-native link in project dir, the fonts were copied correctly.
Executed react-native run-android in project dir.
My Environment
Device: real device, android kitkat v4.4.2
react-native: v0.55.2
react: v16.3.1
yarn: v1.5.1
node: v9.5.0
I want to set fontFamily to roboto thin of my toolbar title.
I have added roboto thin ttf in assets/fonts folder of my android project, however it seems that it is creating issues while running app. I am getting this issue while running
react-native start
ERROR EPERM: operation not permitted, lstat 'E:\Myntra\android\app\build\gener
ated\source\r\debug\android\support\v7\appcompat'
{"errno":-4048,"code":"EPERM","syscall":"lstat","path":"E:\\Myntra\\android\\app
\\build\\generated\\source\\r\\debug\\android\\support\\v7\\appcompat"}
Error: EPERM: operation not permitted, lstat 'E:\Myntra\android\app\build\genera
ted\source\r\debug\android\support\v7\appcompat'
at Error (native)
When I am removing the font then it is working fine.
I am unable to fix this issue. What's the reason?
UPDATE
Many answers are here for adding custom font in react-native for version < 0.60.
For those who are using react-native version > 0.60 , 'rnpm' is deprecated and custom fonts will not work.
Now, in order to add custom font in react-native version > 0.60 you will have to :
1- Create a file named react-native.config.js in the root folder of your project.
2- add this in that new file
module.exports = {
project: {
ios: {},
android: {},
},
assets: ['./assets/fonts']
};
For those running on react-native version < 0.69.x
3- run react-native link command in the root project path.
PS Make sure you have the right path for the fonts folder before running react-native link command
For those running on react-native version >= 0.69.x, Since link is deprecated so react-native link will not work anymore,
the command react-native link is replaced by npx react-native-asset.
More info about the release can be seen here: https://github.com/react-native-community/cli/releases/tag/v8.0.0
Add your fonts file in
Project folder/android/app/src/main/assets/fonts/font_name.ttf
Restart the package manager using react-native run-android
Then you can use your font in your style e.g
fontFamily: 'font_name'
Put all your fonts in you React-Native project directory
./assets/fonts/
Add the following line in your package.json
"rnpm": {
"assets": ["./assets/fonts"]
}
finally run in the terminal from your project directory
$ react-native link
to use it declare this way in your styles
fontFamily: 'your-font-name without extension'
If your font is Raleway-Bold.ttf then,
fontFamily: 'Raleway-Bold'
Update:
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.
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:
Put the downloaded font in the ./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>
STEP 1:
Create a config file at the root of the project named "react-native.config.js"
STEP 2:
Add the following code inside.
module.exports = {
project: {
ios:{},
android:{}
},
assets:['./assets/fonts/'],
}
STEP 3:
Run the following command:
npx react-native link (React-native version < 0.69)
npx react-native-asset (React-native version > 0.69)
Adding Custom Font with EXPO
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
Move your font to asset/fonts folder
From the target component (for example: App.js) load Expo's Font module:
import { Font } from 'expo'
Set a state
this.state = {
fontLoaded: false
}
Load the custom font using componentDidMount:
async componentDidMount() {
await Font.loadAsync({
'ComicSansBold': require('../assets/fonts/ComicSansMSBold.ttf'),
})
this.setState({fontLoaded: true})
}
Finally, use the style attribute to apply the desired font on a component:
{
this.state.fontLoaded
? <Text style={{
fontSize: 48,
fontFamily: 'ComicSansBold'
}}>Glad to Meet You!</Text>
: null
}
Enjoy Coding....
My Output:
RNPM has been merged into React Native core. This means that you don’t need RNPM anymore. So please they don’t want you to use it. Stop using it.
Here are 7 steps broken down to help you set fonts up:
Have your fonts ready, you can download your fonts from GoogleFonts, AdobeFonts, etc. Fonts can be in .ttf, or .otf
Create a configuration file in the root of your project for fonts. Create a file called:
react-native.config.js
Create the folder to house your fonts. You can create a folder called fonts inside the assets folder.
Paste your .ttf or .otf fonts inside of it.
Write a configuration inside of react-native.config.js file, and paste the following:
module.exports = {
assets: ['./src/assets/fonts'],
};
Change the path to the path of the folder housing your fonts.
Now natively set the fonts for Android and IOS. You don’t need to manually do that, just run on your terminal:
react-native link
Any new fonts you add, make sure you run react-native link again on your terminal to natively set the fonts.
#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'],
};
Set in Project.json:
rnpm {
assets:assets/fonts
}
react-native link
For ios:
Add your fonts in given folder structure :
/assets/fonts
and place your fonts in it .
In the root folder . Add a file named
react-native.config.js
copy the code and paste
module.exports = {
assets: [‘./assets/fonts’]
}
you can easily add Google & custom fonts to react native projects via Expo-font.
1-Using google fonts in react native:
import expo-fonts:
import { useFonts, Inter_900Black } from '#expo-google-fonts/inter';
// install pakages related to your favourite font for example:#expo-google-fonts/roboto & etc.
then use this hook at the top of your component hierarchy:
let [fontsLoaded] = useFonts({
Inter_900Black,
});
//fontLoaded indicates the loading state of your font
using font:
<Text style={{ fontFamily: 'Inter_900Black'}}>Inter Black</Text>
2-Using custom fonts in react native:
import expo-fonts:
import { useFonts } from 'expo-font';
use this hook at the top of your component hierarchy:
let [fontsLoaded] = useFonts({
'Custom-Font': require('./assets/fonts/Custom-Font.otf'),
});
using font:
<Text style={{ fontFamily: 'Custom-Font'}}>Inter Black</Text>
Add in project.json file
rnpm {
assets:assets/fonts
}
Then perform react-native link
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.
The correct way
import React from 'react';
import { Text, View } from 'react-native';
import AppLoading from 'expo-app-loading';
import { useFonts } from 'expo-font';
export default props => {
let [fontsLoaded] = useFonts({
'Inter-Black': require('./assets/fonts/Inter-Black.otf'),
});
if (!fontsLoaded) {
return <AppLoading />;
}
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ fontFamily: 'Inter-Black', fontSize: 40 }}>Inter Black</Text>
<Text style={{ fontSize: 40 }}>Platform Default</Text>
</View>
);
};
For react-native version above 0.60, create a react-native.config.js file in the root of the directory and add the below code,
module.exports = {
assets: ['./assets/fonts'],
};
And you should also have the assets folder in root of the directory. Then just run the command npx react-native-asset in your terminal. This is should just work fine.
becareful if assets in src folder
in react-native.config.js file
module.exports = {
project: {
ios:{},
android:{}
},
assets: ['./src/assets/fonts']// assets in src folder
// assets: ['./assets/fonts']// if assets in root use this
}
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" },