React Native Tutorial #17 - Custom Fonts
ฝัง
- เผยแพร่เมื่อ 5 ก.ค. 2024
- Hey gang, in this React Native tutorial we'll be looking at how to use custom fonts in our project.
----------------------------------------
🐱💻 🐱💻 Course Links:
Course files - github.com/iamshaunjp/react-n...
🐱💻 🐱💻 Other Related Courses:
+ Complete React Tutorial - • Complete React Tutoria...
+ React Hooks & Context Tutorial - • React Context & Hooks ...
+ Modern JavaScript Tutorial - • Modern JavaScript Tuto...
THANKYOU! after sitting for several hours trying to use custom fonts in react native i finally found your video!
Amazing tutorial, JUST what I was looking for! I love how you use Functional Components instead of complicated Class Based ones
Thank you!!!!!!!!!!!!!!!!
If you are getting an error with the AppLoading Component
run
expo install expo-app-loading
and the replace
import { AppLoading } from 'expo';
with
import AppLoading from 'expo-app-loading';
The AppLoading component was separated in newer versions of expo
It's giving warning ⚠️
its because it's deprecated and now you can use expo-splash-screen instead, however AppLoading still works; just add an onError attribute like this:
setFontsLoaded(true)}
onError={(err) => console.log(err)}
/>
@@juliorodriguez4946 This was super helpful !
I got some errors because of my files and folders but I solved them and it finally worked ! Thank you so much.
The Net Ninja, your tutorials are brilliant!
In case someone wonder how Home applies the font, is because when fontsLoaded is edited, Home component is re render automatically.
Thank you, very clear tutorial. Love it!
thank you so much!! Exactly what I was looking for.
For those viewing the videos now, Expo no longer supports import AppLoading from "expo", It has changed to
import AppLoading from "expo-app-loading";
also, you'll required onError method inside AppLoading as below.
setFontsLoaded(true)}
onError={console.warn}
/>
cheers!
Class components are my favorite because they're so flexible and potent of doing more than the functional component.
Best tutorial on Custom Fonts
The tutorial is awesome!
In case you are having error, try this solution instead (worked for me):
1. Open terminal and install:
$ expo install expo-font
$ expo install expo-app-loading
2. Use this code instead:
import React from 'react';
import { useFonts } from 'expo-font';
import AppLoading from 'expo-app-loading';
import Home from './screens/Home';
export default function App() {
let [fontsLoaded] = useFonts({
regular: require('./assets/fonts/Nunito-Regular.ttf'),
bold: require('./assets/fonts/Nunito-Bold.ttf'),
});
if (!fontsLoaded) {
return ;
} else {
return ;
}
}
useFonts() works perfectly in my case, feel free to experiment with another method from the documentation.
Thank you for this, i just applied it and it work well for me
Hey Ninja, can you explain why font is different than all other imports in the way that it it's downloaded by 'App' and then can by used across the entire project?
" useEffect(() => {
getFont().then(()=>setfontsLoaded(true))
}, []) " use this its best alternative for that AppLoading component ...i have faced a lots of erros on using AppLoading
Apploading call setfontsLoaded when loading is completed. Can you please explain, how react-native controls flow back to the if condition to check if fontsLoaded is true.
Quick Question:
Any reason why not to just add the custom font as an asset in the React-Native package.json file?
"rnpm": {
"assets": [
"./assets/fonts/"
]
}
Hello! Thanks for the tutorial :)
Do you have any article of including Custom Fonts with react-native-cli?
I have the same question too!
Yes, me to
Thanks. It helped.
Since I am new to RN, I would async the function and do the state, I dont use Expo I guess I should but I dont want to go back and start from beginning.
Thank you for this, Ninja!
helped a lot,thx
A path in an 'extends' option must be relative or rooted, but 'expo-module-scripts/tsconfig.base' is not.
this error message from vscode
but still okay(running app)
this is bug?
you can study the splashscreen instead as apploader is now deprecated
Awesome as usual!
Just an update: now Apploading is imorted like that:
import AppLoading from "expo-app-loading";
Hi...Please, how do you go about this if you are not using expo? I mean using CLI
got this working only after using useFonts as provided in Expo Font documentation
can we use useFont hook instead of the use state
const [fontsLoaded] = useFonts({
'Nunito-Bold': require('./assets/fonts/Nunito-Bold.ttf'),
'Nunito-Regular': require('./assets/fonts/Nunito-Regular.ttf'),
});
it works
Could be possible to achieve this by using useEffect?? Thanks for everything mate!
They updated the documentation and you can now import a custom hook to use the fonts
Same here. I used it and worked the same.
That's what I did and it worked no problem
if you get any errors regarding the installation of expo-app-loading , open cmd as administrator and go to the project directory and then run 'expo install expo-app-loading' instead of installing it from your editor's terminal.
Mine can't import AppLoading.. showing error
This worked, thanks a lot.
Worked for me, Ty sir
Thank you 👏
Hello please I'm following your tutorials and everything is going fine until this point where im getting an error that says that element is invalid when i try to use a custom font
Thanks !
I don't know, but I feel like the way this is being done is not the optimal way to do it. Cause there is the fontWeight property that can be set in the StyleSheet, what about that? I don't want to go about defining each font appending it's 'weight' at the end, there has to be another way to import the font so we can use fontWeight: '700', and it uses the Bold font, and so on.
u tell about the expo and how we can do for the real devices
What if not using expo? what is the AppLoading equivalent?
thanks so much!!!!!!!!!!!!!!!!!!!
Net Ninja's code wouldn't work now. You will run into errors while using AppLoading etc. You will need to import AppLoading like so.
import AppLoading from 'expo-app-loading' . In the AppLoading component, you will also need to and an onError prop. This should take care of it. onError={console.warn}.
Here is my fully working code.
import React, { useState } from 'react';
import * as Font from 'expo-font';
import Home from './screens/home';
import AppLoading from 'expo-app-loading';
const getFonts = () => Font.loadAsync({
'nunito-regular': require('./assets/fonts/Nunito-Regular.ttf'),
'nunito-bold': require('./assets/fonts/Nunito-Bold.ttf')
});
export default function App() {
const [fontsLoaded, setFontsLoaded] = useState(false)
if(fontsLoaded){
return (
);
} else {
return (
setFontsLoaded(true)}
onError={console.warn}
/>
)
}
}
saved me!
@@jasonkim7732 great job, AppLoading is not object anymore.
Thank you so much!
Guys now the expo documentation is updated so
install the following package given below
expo install expo-app-loading
and then copy this code given below
import React, { useState } from "react";
import Home from "./screens/home";
import * as font from "expo-font";
import AppLoading from 'expo-app-loading';
const getFonts = () => {
return font.loadAsync({
"Nunito-Bold": require("./assets/fonts/Nunito-Bold.ttf"),
"Nunito-Regular": require("./assets/fonts/Nunito-Regular.ttf")
})
}
export default function App() {
const [fontsLoaded, setFontsLoaded] = useState(false)
if (fontsLoaded) {
return (
)
}
else {
return (
setFontsLoaded(true)}
onError={()=>console.log("error")}
/>
)
}
}
thank you so much man 💪
This might help to whoever having issues with "Metro has encountered an error: While trying to resolve module `expo-app-loading` " or stuck at "Running application on Android SDK built for x86 stuck" and "fontFamily "nunito-regular" is not a system font.
import React from "react";
import { StyleSheet, Text, View } from "react-native";
import AppLoading from "expo-app-loading";
import { useFonts } from "@use-expo/font";
export default function App() {
const [isLoaded] = useFonts({
"BerkshireSwash-Regular": require("./assets/fonts/BerkshireSwash-Regular.ttf"),
});
if (isLoaded) {
return (
Custom Fonts
);
} else {
return ;
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
});
Some module like AppLoading import from 'expo' is no more.
thank you
🔥🔥🔥
Hello Ninja. U are awesome!!
I would like to ask u: Can i take your videos and make up a tutorial based on your video structure? I am Brazilian and the videos will be in Portuguese.
Thanx a lot!!
Cara, seria incrível! Massa ver outro BR por aqui. Net Ninja realmente manja, seria massa algum conteúdo assim no nosso idioma, vai fundo hehe
Pq vc não traduz?
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `App` :(
im getting the same error . plz help if you find a fix
Sorry guys, I can't help you. I got the same error... If you find out what is the solution please give me a feedback.
@@robimegu3712 no worries , my error got fixed, I misspelled ".ttf" as ".tff"
@@satvic__vichar :D
got the same errror
Nice
I noticed when just doing this course that when importing the fonts I ran into an error. I had to create a react-native.config.js file to import them. Anyone else?
yes
Please help with this step
why cant we just make the getFonts function synchronous?
So useEffect would not have worked for this?
how can i add fonts in non expo project????
Why can't I just import font from google like we do with normal html and css project ?
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: null.
UPDATE: use "import AppLoading from 'expo-app-loading';" at the top after installation (expo install expo-app-loading). Also, besides onFinish, also use
onError={console.warn} (i copy pasted the first comment from the video)
for those who had this kind of message error : you started loading the font nunito-bold but used it before it finished loading ....
just add this line of code in your getFont function like this =>
const getFont= async()=>{
await Font.loadAsync({
'nunito': require('./assets/fonts/Nunito-Bold.ttf')
})}
for people using cli instead of expo
================
1/make a folder in root app as : assets then fonts folder in assets and put .ttf fonts
inside it(./assets/fonts/fontname.ttf)
2/make a file in root and name it: react-native.config.js and pass this inside it.
module.exports = {
project: {
ios: {},
android: {},
},
assets: ['./src/assets/fonts/'],
};
3/ run : npx react-native link
4/ run : npx react-native run-android
(u have to rebuilt the app)
5/ u can now use your font
style={{ fontFamily: "fontname" }}
My text doesn’t show. Does anyone else had the same problem and how did you solve it?
You could just go to the styles and do this:
text:{
fontFamily: 'nunito-bold',
fontSize: 18,
}
It also works
What does .loadAsync do?
Do you have any courses?
Font family "foo-bar" is not a system font and has not been loaded through Font.loadAsync.
☹️☹️☹️☹️
Can i get solution for this?
Try this piece of code for app.js
import React from 'react';
import { AppLoading } from 'expo';
import { Container, Text } from 'native-base';
import * as Font from 'expo-font';
import { Ionicons } from '@expo/vector-icons';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isReady: false,
};
}
async componentDidMount() {
await Font.loadAsync({
Roboto: require('native-base/Fonts/Roboto.ttf'),
Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'),
...Ionicons.font,
});
this.setState({ isReady: true });
}
render() {
if (!this.state.isReady) {
return ;
}
return (
Open up App.js to start working on your app!
);
}
}
@@ShubhamKumar-dp3ex thanks so much for the reply but i got the solution for it we just have to use useFont hook and things get on track👍👍👍🙂🙂🙂
@@super-legend that's nice 🎉
Error "Check the render method of 'App' "
the custom fonts has an error and i dont know to fix it
9:13 that's because stupidly
loll
It didn't work for me and if it didn't work for you too then use this, hope it helps :
app.js -
import React from 'react';
import { Text, View } from 'react-native';
import { useFonts } from 'expo-font';
import Home from './screens/home'
export default props => {
let [fontsLoaded] = useFonts({
'Nunitobold': require('./assets/fonts/Nunitobold.ttf'),
'NunitoRegular': require('./assets/fonts/NunitoRegular.ttf'),
});
return (
);
};
home.js -
import React from 'React';
import { StyleSheet, View, Text } from 'react-native';
export default function Home() {
return (
Home Screen
)
}
const styles = StyleSheet.create({
container: {
padding: 24,
},
titleText: {
fontFamily: 'Nunitobold',
fontSize: 18,
}
});
(keep the .ttf font file name and the name in code same obviously)
Right
FACING THIS ISSUE...CAN ANYONE HELP?
fontFamily "nunito-bold" is not a system font and has not been loaded through Font.loadAsync.
- If you intended to use a system font, make sure you typed the name correctly and that it is supported by your device operating system.
- If this is a custom font, be sure to load it with Font.loadAsync.
try import font from the top instead of using require method like below:
import React, { useState } from "react";
import * as Font from "expo-font";
import Home from "./screens/home";
import AppLoading from 'expo-app-loading';
import Defago from './assets/fonts/DefagoNotoSans.ttf';
const getFonts = () => {
return Font.loadAsync({
'Defago': Defago,
});
};
export default function App() {
const [fontLoaded, setFontLoaded] = useState(false);
if (fontLoaded) {
return (
);
} else {
return (
setFontLoaded(true)} onError={console.warn}/>
);
}
}
@@user-il3gd9er1u Hey thanks, it worked!
Unable to resolve "./assets/fonts/
check the path again. i had the same error and then noticed that the path i had written was wrong.
I am unable to solve this error. if anybody can solve it, I will be very helpful
F:/FYP/apps/gamezone/node_modules/expo-splash-screen/build/index.js
Error: ENOENT: no such file or directory, open 'F:\FYP\apps\gamezone
ode_modules\expo-splash-screen\build\index.js'
This error occurred during the build time and cannot be dismissed.
Building JavaScript bundle: error
ERROR
14:13
Unable to resolve module expo-app-loading from J:\React_Native_Projects\gameZone\App.js: expo-app-loading could not be found within the project.
If you are sure the module exists, try these steps:
1. Clear watchman watches: watchman watch-del-all
2. Delete node_modules and run yarn install
3. Reset Metro's cache: yarn start --reset-cache
4. Remove the cache: rm -rf /tmp/metro-*
3 | import * as Font from 'expo-font';
4 | import Home from './screens/home';
> 5 | import { AppLoading } from 'expo-app-loading';
| ^
6 |
7 | const getFont = () => Font.loadAsync({
8 | 'nunito-regular': require('./assets/fonts/Nunito-Regular.ttf'),
Expo has been updated, you WILL get an error go down to Ovos Odius comment to fix
This film is unfortunately already deprecated.
Hello, i just wasted about 3 to 4 hours realizing why my fonts didnt work corectly and would like to advise whoever could fit:
be sure your fonts file name is as simple as possible, mine wasnt woring due a "=" signal on it
also, in else section add the onError prop >>>> onError={ () => getFonts }
it should look like this:
else {
return(
getFonts}
onFinish={()=>setFontsLoaded(true)}
/>
)
}
Either, if the error persists, try creating a new project using ONLY expo tools; like when you add a new package in your cmd, use ever the > expo install whatever-package-name-is-comes-here <
i have had some issues due installing some libraries from using EXPO INSTALL and some using NPM INSTALL
chose one of the installation methods for the whole project
Thanks a lot. This code helped me in getting rid of the error too!
The error was " apploading threw an unexpected error when loading:"
very useful
useFonts made it easier
I encountered a problem with expo-splash-screen. Anybody having this problem simply run "npm install --save expo-splash-screen" It will save it as a dependency in the package.json. Thanks
not work in me, thanks for the tutorial
I did all of that but font does not change ( No errors, nothing... (
If your using a AVD you might want to close it and open a new one. for some reason if i have had mine up for a while it just stops working and get buggy.
@@justinuzzanti361 I use physical device
is your code on github, can you give a link to repo if you are not yet resolved the issue?
@@begoalibasic841 Did not resolve yet... github.com/grebennikovalex/XO/blob/master/App.js Thank you )
@@begoalibasic841 Custom font appeared only in Input field... as an input string and as well as a placeholder ) weird...
It works for me even without return statement in else block. I dont know how...
It didn't work for me, maybe because this is an outdated form of importing fonts. I have found another solution using useFonts() hook:
import React from 'react';
import { View, Text } from 'react-native';
import { useFonts } from 'expo-font';
import Home from './screens/home';
export default function App() {
const [fontsLoaded] = useFonts({
"nunito-regular": require("./assets/fonts/Nunito-Regular.ttf"),
"nunito-bold": require("./assets/fonts/Nunito-Bold.ttf"),
});
if (!fontsLoaded) {
return (
Loading fonts...
);
} else {
return (
);
}
}
Cheers! Thanks for the help.
@@kazirafidraiyan2553 you're welcome👌
Thanks! I tried a number of different options, including what was given on Expo Docs Fonts page. This was the first thing that worked for me.
not working on me, I think have to study splash screen
I didn't use splash screen to optimize the render, just the code below I used to import the custom font work as well.
const customerFonts={
'Inter-Black': require('./assets/fonts/Inter-Black.ttf'),
'Inter-Light': require('./assets/fonts/Inter-Light.ttf'),
'Inter-Medium': require('./assets/fonts/Inter-Medium.ttf'),
'Inter-Regular': require('./assets/fonts/Inter-Regular.ttf'),
}
export default function App() {
const [fontLoaded, setFontLoaded] = useState(false)
useEffect(()=>{
const getFonts=async()=>{
try{
await Font.loadAsync(customerFonts)
}catch(e){
console.warn(e);
}finally{
setFontLoaded(true)
}
}
getFonts();
},[])
wrap the app in the fontLoaded condition is true, else return null.
For those who are watching now! You don't need to download the fonts. First import it like this: "expo install @expo-google-fonts/nunito expo-font"
import React from 'react';
import Home from './screens/Home';
import { StyleSheet, Text, View } from 'react-native';
import { useFonts, Nunito_400Regular, Nunito_700Bold } from '@expo-google-fonts/nunito';
export default function App() {
let [fontsLoaded] = useFonts({
Nunito_700Bold,
Nunito_400Regular,
});
if (!fontsLoaded) {
return (
Internet Required!
)
} else {
return (
);
}
}
const styles = StyleSheet.create({
container: {
padding: 50,
flex: 1,
textAlignVertical: "center",
}
})
Using this code, it run perfectly :
import * as React from 'react';
import * as Font from 'expo-font';
import Home from './screens/home';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fontsLoaded: false
}
}
async loadFonts() {
await Font.loadAsync({
'nunito-bold': require('./assets/fonts/Nunito-Bold.ttf'),
});
this.setState({ fontsLoaded: true });
}
componentDidMount() {
this.loadFonts();
}
render() {
if (this.state.fontsLoaded) {
return (
);
} else {
return null;
}
}
}
This works.
Unable to resolve "./assests/fonts/Nunito-Regular.ttf" from "App.js"
this error is appearing in App builder
same error any solution?
did you find the answer?
make sure you are using "useState" correctly
useEfeect so ez
I would not recommend this way of using styles because the whole time this was the reason that my app keep reloading. Sorry!
I get this error:
- fontFamily "nunito-regular" is not a system font and has not been loaded through Font.loadAsync.
- If you intended to use a system font, make sure you typed the name correctly and that it is supported by your device operating system.
- If this is a custom font, be sure to load it with Font.loadAsync.
I followed the guide carefully and tried many stack overflow solutions. Any help is appreciated.
Same here :(
Same here. Someone kindly help, will be obliged!!
Didn't worked 🥺
+1
@@amanxsharma20 I solved apploadig component error
@@adityapatil3425 I also had the same error. I just deleted the app loading thing and it worked fine afterward. maybe sort the comments by recent and check my recent comment and provide some insights if u can. I've pasted the whole code.
If you are learning like me in 2022 : Here you should make a small modification like so :
- After running this command :
> expo install @expo-google-fonts/inter expo-font
> expo install expo-app-loading
- Delete node_modules folder and run :
> npm install or yarn install
And do this 👇👇👇👇👇👇👇
------------------------------------------------------------------------------------------------------
1 - import useFont:
import { useFonts } from 'expo-font';
------------------------------------------------------------------------------------------------------
2 - Change import app loading location :
import AppLoading from 'expo-app-loading';
------------------------------------------------------------------------------------------------------
3 - Change the getFont function to :
const getFont = () => useFonts({
'Nunito-Bold': require('./assets/fonts/Roboto-Bold.ttf'),
})
------------------------------------------------------------------------------------------------------
4 - My conditions :
if (fontsLoaded) {
return (
);
} else {
return (
)
}
5 - have a nice day ;p and don't forget Ninja is the best
Good Code.....
It’s work for me.