I am new to react native and I followed a basic course on react-native but the course did not speak about adding fonts to your app and I was wondering if it was possible to do so.
Hi if you are using expo for your React-Native project, u should try following steps:
Install Expo-Font Package
2.Import useFonts hook from expo fonts import { useFonts } from "expo-font";
3.Import All your local fonts:
//fontsLoaded returns boolean u can check this and render application conditionaliy
let [fontsLoaded] = useFonts({
GEO_UltLt: require("./assets/fonts/mainfont/UltLt.ttf"),
GEO_Thin: require("./assets/fonts/mainfont/Thin.ttf"),
GEO_Light: require("./assets/fonts/mainfont/Light.ttf"),
GEO_Medium: require("./assets/fonts/mainfont/Medium.ttf"),
GEO_Bold: require("./assets/fonts/mainfont/Bold.ttf"),
GEO_Heavy: require("./assets/fonts/mainfont/Heavy.ttf"),
GEO_Black: require("./assets/fonts/mainfont/Black.ttf"),
});
4.And use inside app like this
//inside app
input: {
flex: 1,
color: "#323f4b",
fontFamily:"GEO_Medium"
}
I have encountered a bug with react-native's Stylesheet component. It causes my iphone simulation to stay stuck on expo's logo after loading the js bundle. No errors to be found.
import { Text, View, StyleSheet } from "react-native"
var styles = StyleSheet.create({
innerText: {
color: 'red',
}
})
export var TestComponent = function() {
return (<View><Text style={styles.innerText}>NOW Lets get this working</Text></View>)
}
If I just put the style inline, it works and renders correctly. No freezing after bundle loading.
return (<View><Text style={{color:'red'}}>NOW Lets get this working</Text></View>
One thing to note is that this TestComponent is coming from a node_module. Stylesheet's work as expected in the app's codebase, but fail when coming from this node_module.
The module that exports the TestComponent was using react-native 0.68.0, but the app that uses the module was using react-native 0.64.3. When I downgraded the module to the same react-native version, it worked.
It also worked when updating the app's version instead of downgrading the other, but this time expo gives a warning: Warning: Invalid version react-native#0.68.1 for expo sdkVersion 44.0.0. Use react-native#0.64.3
I'm developing an app using React and Electron.
I'm storing the images in src/assets/images. When I run the app in development using react-scripts start and electron . everything works fine.
The problem occurs when the react app is built using react-scripts build. When the first view is loaded the path is correctly resolved, for example file:///D:/Projects/app-name/build/static/media/logo.e99ed458.png and the image is displayed.
Now, when the route changes, the image no longer works. In the network tab in devTools the request URL is file:///D:/main/static/media/logo.e99ed458.png which is obviously incorrect.
This is my component code:
import React from "react";
import Logo from '../../assets/images/ad.png';
const Logo = () => {
return (
<React.Fragment>
<img src={Logo} alt="no image" />
</React.Fragment >
);
};
export default Logo;
And in electron.js
mainWindow.loadURL(url.format({
protocol: 'file',
slashes: true,
pathname: require('path').join(__dirname, '../build/index.html')
}));
I've been trying to solve this problem for two days now. Does anyone know a solution?
EDIT:
I have also tried using PUBLIC_URL according to https://create-react-app.dev/docs/using-the-public-folder/
But the result is the same, the path is resolved correctly when the first view is displayed and after that it resolves to file:///D:/assets/images/logo.png.
When I log process.env.PUBLIC_URL it says that PUBLIC_URL is equal to ".".
I solved this issue by changing the routers instead of using BrowserRouter you should use HashRouter
This article https://www.freecodecamp.org/news/building-an-electron-application-with-create-react-app-97945861647c/ has a good example but Does not have the configurations of routers
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" },
I've been having errors after errors to the point where I've reset my Metro Bundle and performed updates, errors from required module "699" to "700" have been coming up and now this. I believe I have all the required dependencies for Drawer navigator and ionicicons but errors continue to persist. I have code written in different files but below is the one written in App.js. Feel free to ask for the other ones in order to solve the issue at hand.
import React from 'react';
import {
View,
Text,
StyleSheet
} from "react-native" ;
import DrawerNavigator from './Menu/DrawerNavigator';
import SettingScreen from './Menu/SettingScreen'
export default class App extends React.Component {
render(){
return (
<View style ={style.container}>
<SettingScreen/>
</View>
);
}
}
style = StyleSheet.create ({
container: {
flex: 1,
justifyContent: 'center',
},
});
For mac,
I have this error, I believe that you have npm install/yarn add a new package and you will require to Ctrl+C to exit the Metro Bundler and restart again. The error/issue will be solved.
For Windows,
I got the same error, what I did is
close your local-cli windows(picture attached)
uninstall the app from your device/emulator(there can be two apps with the slight change name of theirs).
run again the with react native command like 'react-native run-android'
I tried to reproduce it after these steps but I wasn't able
For Windows 10:
Restarting the Metro Bundler by pressing ctrl + c and then expo start will fix this issue.