How to add custom font in react native android - android

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" },

Related

Android Use fonts for dependency package

I am very new to mobile development. I am trying to use a downloaded font in my react native package. I searched online. The answers are similar, which ask me to create a font folder and put it under src/main/assets/font, but there is no android folder in my package since it is only a dependency package of the main project. I can only run it from the main project. I tried to add font folder under assets folder in main project, but it's not working. I am wondering if I miss any steps? Or is there any way that I can add the font in my own package, but not under android folder? And due to company security, I cannot use npx or npm to link.
Yes, You will have to make a folder with the name of fonts in assets folder like I did
Now, download the fonts
import * as Font from "expo-font";
import AppLoading from "expo-app-loading";
const fetchFont = () => {
return Font.loadAsync({
"open-sans": require("./App/assets/Fonts/open-sans.regular.ttf"),
"open-sans-bold": require("./App/assets/Fonts/open-sans.bold.ttf"),
});
};
export default function App() {
const [fontLoaded, setFontLoaded] = useState(false);
if (!fontLoaded) {
return (
<AppLoading
startAsync={fetchFont}
onFinish={() => setFontLoaded(true)}
onError={(err) => console.log(err)}
/>
);
}
return (
<Provider store={store}>
<MealsNavigator />
</Provider>
);
}
Use like below code
title: {
fontFamily: "open-sans-bold",
fontSize: 20,
color: "white",
textAlign: "center",
alignItems: "center",
},
});

How to use svg images on react-native?

I'm trying to use svg images on my native react application, I'm developing on Android.
So I followed this tutorial =>
https://medium.com/faun/add-custom-svg-icons-to-your-expo-app-279b492f6a15
I have an error Unable to read the 'fill' property of undefined while I manage to display the image, so I try to downgrade the version of react-native- svg and the image is displayed but as soon as I integrated react-navigation my application expo on crash at startup.
So I looked for a long time for the cause of this crash.
I tried to delete the react-native-svg library, the metroconfig.js file, and expo worked again, I don't know if this was the cause of the problem.
I would like to know if people have encountered these problems or if not what is the best method which works with the current version of RN to import a svg image in a react-native application?
Thank you in advance for your help and your answers.
EDIT
I tested react-native-svg and react-native-transformer-svg with the latest version of react native / expo / sdk expo
From the moment I create the metro.config.js file and link it with expo by updating the app.json file, my expo application crashes at startup.
I had to use react-native-svg without react-native-transformer-svg, that is to say that I have to convert an SVG file into a reactable SVG file.
If someone has a working solution to import svg files automatically, it would be of great help to me.
Important Note - I develop on a real Android device, not in Expo!
Here is some code from an issue opened on Github that actually worked for me after some modification.
Link to Github issue
In my metro.config.js file I finally have this code:
const { getDefaultConfig } = require("metro-config")
module.exports = (async () => {
const {
resolver: { sourceExts, assetExts },
} = await getDefaultConfig()
// here I extend the extensions needed for RN because I use JSX.
// you don't need this if you use pure JS files
const updatedSourceExts = [...sourceExts, "jsx", "js", "json", "ts", "tsx"]
return {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
babelTransformerPath: require.resolve("react-native-svg-transformer"),
},
resolver: {
assetExts: assetExts.filter((ext) => ext !== "svg"),
sourceExts: [...updatedSourceExts, "svg"],
},
}
})()
A part of my package-json file:
"react-native": "0.63.2",
"react-native-svg": "^12.1.0",
"react-native-svg-transformer": "^0.14.3"
Install react-native-svg-transformer
npm i react-native-svg-transformer --save
I'm using SVG as following and it works fine
import LOGOSVG from "assets/svg/logo.svg"
in render
<View>
<LOGOSVG
width="100%"
height="70%"
/>
</View>

Error while trying to access files in the app

I'm building a react-native app that uses tensorflow to recognize images, I'm following the steps in this tutorial.
I did everything according to the explanations, including the part of "Fetching files". I created the assets folder and put the files in it (the path is correct).
But when I run this code:
const tfImageRecognition = new TfImageRecognition({
model: require('./assets/tensorflow_inception_graph.pb'),
labels: require('./assets/tensorflow_labels.txt'),
});
The app gives the following error:
I already tried to create a new project, I imported the react-native-tensorflow import { TfImageRecognition } from 'react-native-tensorflow';, I updated the cache, I deleted the folder node_modules and also I created the file "rn-cli.config.js" that is requested in the tutorial to give access to the files in the assets folder. Any idea how to fix this?
I'm using expo to run the app on mobile (android).
npm: 5.51
expo: 51.4.0
react-native: 0.54.0
react-native-cli: 2.0.1
This problem didn't occur with me. Try react-native start --reset-cache and then run the app again.
There is a better way to this.
import model from './assets/tensorflow_inception_graph.pb';
import labels from './assets/tensorflow_labels.txt';
const tfImageRecognition = new TfImageRecognition({
model,
labels
});
Restart your server.
I tried the same example as you mentioned I got accessed Image and Text.
I stored files inside assets in the same directory. Can you share code to produce an error that you faced?
async recognizeImage() {
try {
const tfImageRecognition = new TfImageRecognition({
model:require('./assets/tensorflow_inception_graph.pb'),
labels: require('./assets/tensorflow_labels.txt')
})
const results = await tfImageRecognition.recognize({
image: this.image
})
const resultText = `Name: ${results[0].name} - Confidence: ${results[0].confidence}`
this.setState({result: resultText})
await tfImageRecognition.close()
} catch(err) {
alert(err)
}
}
As you mentioned your using expo then I'm assuming that run npm eject already. As react-native-tensorflow this library require native changes
You must add extensions in your rn-cli.config.js, in order to require tensorflow_inception_graph.pb and tensorflow_labels.txt
module.exports = {
getAssetExts() {
return ['pb', 'txt']
}
}
Replace ./ with so ../ , so final code will be -
model: require('../assets/tensorflow_inception_graph.pb'),
labels: require('../assets/tensorflow_labels.txt')

Icon not displaying on screen android using react-native-vector-icons

I am using create-react-native-app. I want to use react-native-vector-icons
But its not showing anything on android screen (I am viewing it on expo app)
Here is what I did:
App.js:
const Courses = TabNavigator({
ReactCourses: { screen: ReactCourses },
NativeCourses: { screen: NativeCourses },
}, {
tabBarOptions: {
activeTintColor: '#e91e63',
swipeEnabled: true,
showIcon:true,
},
});
ReactCourses.js:
import Icon from 'react-native-vector-icons/MaterialIcons';
static navigationOptions = {
tabBarLabel: 'React Courses',
tabBarIcon:({ tintColor }) => (
<Icon
name={'home'}
size={26}
style={[styles.icon, {color: tintColor}]} />
)
}
Add the following things in android/app/build.gradle
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
And then execute the command
react-native run-android
When using Create React Native App, it's not possible to use react-native link with native module packages. Because CRNA projects are loaded in the Expo client app, you'll want to follow the relevant documentation to get vector icons working in your project.
Also, make sure that you're using the Expo preset in .babelrc. It should look like the one provided in the template project.
I think what you did is just a half thing, so after running npm install did you link the project with the third party's native code by running react-native link? if yes, did you rebuild the project by going to android studio and hit play button?if yes then just restart your packager and we are good to go...
Cheers :)

React-Native: Module AppRegistry is not a registered callable module

I'm currently trying to get the ES6 react-native-webpack-server running
on an Android emulator. The difference is I've upgraded my package.json and build.grade to use react 0.18.0, and am getting this error on boot. As far as I'm aware AppRegistry is imported correctly. Even if I were to comment out the code this error still comes up. This does work on iOS without issue.
What am I doing wrong?
EDIT: After trying other boilerplates that do support 0.18.0, I'm still coming across the same issue.
i just upgraded to react-native 0.18.1 today tough having some peer dependencies issues with 0.19.0-rc pre-release version.
Back to your question, what I did was
cd android
sudo ./gradlew clean (more information about how clean works here)
then back to the working directory and run
react-native run-android
you should restart your npm too after that upgrade.
hope this works for you.
I had the same issue on iOS and the cause for me was that my index.ios.js was incorrect (because I copy-pasted one of the examples without looking at its contents), it was ending with a module export declaration
exports.title = ...
exports.description = ...
module.exports = MyRootComponent;
Instead of the expected
AppRegistry.registerComponent('MyAppName', () => MyRootComponent);
You could have the same issue on android with the index.android.js I guess.
The one main reason of this problem could be where you would have installed a plugin and forget to link it.
try this:
react-native link
Re-run your app.
Hope this will help. Please let me know in comments. Thanks.
For me just restarting the computer fixed it.
(My error was "module appRegistry is not a registered callable module (calling runapplication) js engine: hermes")
Another top answer that is missing here and might have worked was just to kill node processes:
killall -9 node
[ Module AppRegistry is not registered callable module (calling runApplication) ]
I solved this issue just by adding
import { AppRegistry } from "react-native";
import App from "./App";
import { name as appName } from "./app.json";
AppRegistry.registerComponent(appName, () => App);
to my index.js
make sure this exists in your index.js
For me my issue was putting the wrong entry-file when bundling.
I was using App.js as my entry-file, hence the App couldn't find AppRegistry
Correct:
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/
Incorrect:
react-native bundle --platform android --dev false --entry-file App.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/
I had this issue - across iOS & Android, developing on Mac - after I had been fiddling with a dependency's code in the node_modules dir.
I solved it with:
rm -rf node_modules
npm i
npx pod-install ios
Which basically just re-installs your dependencies fresh.
Hopefully this can save someone a headache. I got this error after upgrading my react-native version. Confusingly it only appeared on the android side of things.
My file structure includes an index.ios.js and an index.android.js. Both contain the code:
AppRegistry.registerComponent('App', () => App);
What I had to do was, in android/app/src/main/java/com/{projectName}/MainApplication.java, change index to index.android:
#Override
protected String getJSMainModuleName() {
return "index.android"; // was "index"
}
Then in app/build/build.gradle, change the entryFile from index.js to index.android.js
project.ext.react = [
entryFile: "index.android.js" // was index.js"
]
If you are facing this error in windows with android
open your root directory app folder and move into android folder .
cd android
gradlew clean
start your app again
react-native run-android
I don't know why, but when I move AppRegistry.registerComponent from the index.js file that is included in index.android.js to reside inside index.android.js directly, it seems to work.
restart packager worked for me.
just kill react native packager and run it again.
Check to see if you are not directly rendering something inside SafeAreaView
Ensure you are following this format
<SafeAreaView>
<View>
{children}
</View>
</SafeAreaView>
If you are using some of the examples they might not work
Here is my version for scroll view
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
View,
ScrollView,
TouchableOpacity,
Image
} from 'react-native';
class AwesomeProject extends Component {
render() {
return (
<View>
<ScrollView
ref={(scrollView) => { _scrollView = scrollView; }}
automaticallyAdjustContentInsets={false}
onScroll={() => { console.log('onScroll!'); }}
scrollEventThrottle={200}
style={styles.scrollView}>
{THUMBS.map(createThumbRow)}
</ScrollView>
<TouchableOpacity
style={styles.button}
onPress={() => { _scrollView.scrollTo({y: 0}); }}>
<Text>Scroll to top</Text>
</TouchableOpacity>
</View>
);
}
}
var Thumb = React.createClass({
shouldComponentUpdate: function(nextProps, nextState) {
return false;
},
render: function() {
return (
<View style={styles.button}>
<Image style={styles.img} source={{uri:this.props.uri}} />
</View>
);
}
});
var THUMBS = [
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1,
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1,
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1
];
THUMBS = THUMBS.concat(THUMBS); // double length of THUMBS
var createThumbRow = (uri, i) => <Thumb key={i} uri={uri} />;
var styles = StyleSheet.create({
scrollView: {
backgroundColor: '#6A85B1',
height: 600,
},
horizontalScrollView: {
height: 120,
},
containerPage: {
height: 50,
width: 50,
backgroundColor: '#527FE4',
padding: 5,
},
text: {
fontSize: 20,
color: '#888888',
left: 80,
top: 20,
height: 40,
},
button: {
margin: 7,
padding: 5,
alignItems: 'center',
backgroundColor: '#eaeaea',
borderRadius: 3,
},
buttonContents: {
flexDirection: 'row',
width: 64,
height: 64,
},
img: {
width: 321,
height: 200,
}
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
I uninstalled it on Genymotion. Then run react-native run-android to build the app. And it worked. Do try this first before running sudo ./gradlew clean, it will save you a lot of time.
npm start -- --reset-cache
Probably port is already in use. I face similar issue when i first run react-native run-android and then npm start. I solve it like this: First, get the id of the process running in port 8081:
sudo lsof -i :8081
I had the same problem several times. The following solutions are solved my problem. I have listed out them according to complexity.
Restart the computer and see whether the problem is out
If it still exists, try to kill the process on running port usually 8080
netstat -ano | findstr 8080
taskkill /F /PID <PID>
If it still exists, go to 'android' directory as follow and go further
cd android
./gradlew clean
and start node
npm start
then run npx react-native run android or expo stat and press 'a'
Hope you will OK with the above issues.
My issue was cleared by following these commands (OS: Windows 10).
cd android
gradlew clean
cd..
npx react-native run-android
Please use Below mention : pakage
"react-native-reanimated": "^2.2.4",
I had the same problem and that because I was calling Stylesheet without importing..
In my case, my index.js just points to another js instead of my Launcher js mistakenly, which does not contain AppRegistry.registerComponent().
So, make sure the file yourindex.jspoint to register the class.
My issue was fixed by increasing my inotify max_user_watches:
sudo sysctl fs.inotify.max_user_watches=1280000
For me it was a issue with react-native dependency on next version of react package, while in my package.json the old one was specified. Upgrading my react version solved this problem.
For me just i linked with react native as this way : react-native link
I got this error in Expo because I had exported the wrong component name, e.g.
const Wonk = props => (
<Text>Hi!</Text>
)
export default Stack;
I solved this problem by doing the following:
cd android
./gradlew clean
taskkill /f /im node.exe
uninstall app from android
If you are using windows machine you need to do cd android then ./gradlew clean then run react-native run-android
This can because of any cache issue from node, pod ,gradle anywhere, its better to do an entire clean slate cleanup, for this use react native clean project
A typical reason I get this error is when I import badly a component (like with the wrong name). Same if I export it badly and them import it correctly. This may seem primitive but to err is human and many times this error appears, if cleaning the project and restarting it doesn't fix it, it can be this.
delete android/.gradle and reac-module.
than run yarn install and run-android
on iOS I have got this issue.
but after cleaning the build
folder by entering command+shift+k and building it again worked for me
you should also check the scheme should be debug

Categories

Resources