added font to react native
How to Add Fonts to React Native
If you're building a React Native app, you might be wondering how to add custom fonts to your project. In this article, I will walk you through the process of adding fonts to your React Native project.
Step 1: Add the Font Files to Your Project
The first step is to add the font files to your project. You can do this by creating a new folder in your project directory called fonts
, and then placing the font files (in .ttf or .otf format) in that folder.
<div class="highlight"><pre>
my-react-native-app/
__tests__/
android/
ios/
fonts/
my-font-regular.ttf
my-font-bold.ttf
node_modules/
src/
package.json
</pre></div>
Step 2: Link the Font Files
The next step is to link the font files in your project. You can do this by adding the following code to your react-native.config.js
file:
<div class="highlight"><pre>
module.exports = {
assets: ['./fonts/'],
};
</pre></div>
This tells React Native to look for assets in the fonts
directory.
Step 3: Import the Font Files
The final step is to import the font files into your React Native components. You can do this by using the Font.loadAsync()
method provided by the expo-font
package.
<div class="highlight"><pre>
import React, { useState, useEffect } from 'react';
import { Text } from 'react-native';
import * as Font from 'expo-font';
const App = () => {
const [fontLoaded, setFontLoaded] = useState(false);
useEffect(() => {
const loadFonts = async () => {
await Font.loadAsync({
'my-font-regular': require('./fonts/my-font-regular.ttf'),
'my-font-bold': require('./fonts/my-font-bold.ttf'),
});
setFontLoaded(true);
};
loadFonts();
}, []);
return (
<>
{fontLoaded ? (
<Text style={{ fontFamily: 'my-font-regular' }}>
Hello, World!
</Text>
) : null}
</>
);
};
export default App;
</pre></div>
In this example, we're using the useState()
hook to keep track of whether the fonts have loaded. We're then using the useEffect()
hook to load the fonts when the component mounts.
We're also using the <>
shorthand for <React.Fragment>
, which allows us to return multiple components without wrapping them in a <View>
component.
Finally, we're using the fontFamily
property to apply the custom font to our <Text>
component.
Conclusion
Adding custom fonts to your React Native project is a great way to improve the look and feel of your app. By following the steps outlined in this article, you can easily add custom fonts to your project and start using them in your components.