I'm trying to load a custom font from my assets folder within my project. I've looked up online and so far after doing all the steps, I'm still faced with the same issue.
I've added the source of the fonts into my package.json file like this:
"rnpm": {
"assets": [
"./assets/fonts/"
]
}
I've imported expo-font into my project as well, and I'm simply calling the fontFamily like this:
<Text style={{ textAlign: 'center', fontFamily: 'Montserrat-Regular', fontSize: 20 }}>Home</Text>
am I missing something?
EDIT: I forgot to mention that I'm using a custom font in another screen, the exact same way...yet this screen is giving me issues.
The files I am using are Montserrat-Regular.tff, Montserrat-Bold.tff, and Montserrate-Light.tff
The path for these files are MyProject/assets/fonts/MyFonts.ttf
You don't have an Android folder, so it looks like you're using Expo, not React Native.
So I'll show you how to do Expo.
Take the Open Sans zipfile that you downloaded, extract it and copy
Montserrat-Regular.ttf into the assets directory in your
project. The location we recommend is your-project/assets/fonts.
and you can run expo install expo-font
Add the following import in your application code in App.js: import * as Font from 'expo-font';
The expo library provides an API to access native functionality of
the device from your JavaScript code. Font is the module that deals
with font-related tasks. First, we must load the font from our
assets directory using Font.loadAsync(). We can do this in the
componentDidMount() lifecycle method of the App component. Add the
following method in App: Now that we have the font files saved to
disk and the Font SDK imported, let's add this code:
export default class App extends React.Component {
componentDidMount() {
Font.loadAsync({
'Montserrat-Regular': require('./assets/fonts/Montserrat-Regular.ttf'),
});
}
// ...
}
This loads Open Sans Bold and associates it with the name 'Montserrat-Regular' in Expo's font map. Now we just have to refer to this font in our Text component.
Note: Fonts loaded through Expo don't currently support the fontWeight or fontStyle properties -- you will need to load those
variations of the font and specify them by name, as we have done here
with bold.
Check your Info.plist file from the iOS folder and looking for a UIAppFonts key, you should see something similar to:
<key>UIAppFonts</key>
<array>
<string>Montserrat Regular.ttf</string>
</array>
Also, your style will be like this;
fontFamily: "Montserrat", instead fontFamily: "Montserrat-Regular".
I managed to fix the issue I was having. It seems I needed to give the app a moment to load the font, still not sure why this was giving me the issue, but here is what my working code looks like now in case anybody else is having the same problem
This is the code I added into the screen in which I was trying to load my custom font.
constructor(props) {
super(props);
this.state = {
fontLoaded: false
}
}
async componentDidMount(){
await Font.loadAsync({
'Montserrat': require('../assets/fonts/Montserrat.ttf'),
}).then(() => {
this.setState({fontLoaded: true})
})
}
<View>
{ this.state.fontLoaded == true ? (
<Text style={{ fontSize: 40, fontFamily: 'Montserrat', color:'white', marginLeft: 10}}>Home</Text>
) : (<Text> Loading...</Text>)
}
</View>
Related
I am having a issue on react native. This is my first time using so I am following a guide from https://www.youtube.com/watch?v=f6TXEnHT_Mk. According to the video, after npm start, I am suppose to arrive with a browser opened that look like:
But it did not happen on my laptop. When I tried to copy the link in the terminal to a browser, I get this instead:
Can anyone explain to me what did I do wrong? I have double checked everything and is the same as the video till this point. In the video for this to appear the window defender firewall was blocking the feature so the user allow access for that. But my firewall seems to not be blocking it
Having error logging in expo via terminal:
Solved
I am currently following a guide which is from https://www.youtube.com/watch?v=ql4J6SpLXZA
I am doing the login UI and around the 8 min mark, i decided to take a short break. After coming back, I continued till the 9 min mark and i am met with this:
Tried to remove the code I newly added but the problem still did not go away.
Referring to Unable to resolve "../../App" from "node_modules/expo/AppEntry.js", tried to add
"sourceExts": [ "js", "json", "ts", "tsx", "jsx", "vue"]
in the app.json file but I do not have the
packageOpts line in the file. How do i solve this?
Solved
I am still following the guide above: https://www.youtube.com/watch?v=ql4J6SpLXZA.
Now I am having issue with firebase. As stated in the video, it is for firebase 8 and I am using firebase 9 so I used the code provided by firebase:
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyDI9Ggk4h-bHBSDjZAZgMaB6Ur_lvJIPKw",
authDomain: "fypapp-4f10a.firebaseapp.com",
projectId: "fypapp-4f10a",
storageBucket: "fypapp-4f10a.appspot.com",
messagingSenderId: "306492584822",
appId: "1:306492584822:web:24b7ccb717a107df6b4057"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
With this I was having an error of
Unable to resolve "idb" from "node_modules\#firebase\app\dist\esm\index.esm2017.js"
And I found a answer from online to bypass that by creating metro.config.js with the code: (This is for future user that is having trouble with this error)
const { getDefaultConfig } = require("#expo/metro-config");
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push("cjs");
module.exports = defaultConfig;
But now I am having another error when creating new user. I have the following error :
TypeError: undefined is not an object (evaluating '_firebase.auth.createUserWithEmailAndPassword')
I searched around stack and no one has post error of
evaluating '_firebase.auth.createUserWithEmailAndPassword`
Is there something I can do to solve this?
Another problem I have is regarding the styling for the page,
I have this currently: (When i never attempt to type anything new in the input boxes)
When i try to type something new in the input boxes:
I have the following code: How do i correct it so that my keyboard can be seen and the input boxes can be seen at the same time?
<KeyboardAvoidingView //To prevent keyboard from blocking the writing area
style={styles.container}
behavior = "padding"
>
<View style = {styles.inputContainer}>
<TextInput
placeholder = "Email"
value={email}
onChangeText ={text => setEmail(text)}
styles = {styles.input}
/>
<TextInput
placeholder = "Password"
value={password}
onChangeText ={text => setPassword(text)}
styles = {styles.input}
secureTextEntry //Hide password
/>
</View>
<View style = {styles.buttonContainer}>
<TouchableOpacity
onPress = {() => { } }
style = {styles.button}
>
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity>
<TouchableOpacity
onPress = {handleSignUp}
style = {[styles.button, styles.buttonOutline]}
>
<Text style={styles.buttonOutlineText}>Register</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
Update July 25, 2022: expo-cli#6.0.0 has been released with the web
UI removed. The last release to include the web UI is
expo-cli#5.5.1.
You can check this article in medium for more details from here.
Or you can check this old question from here.
I prefer to change the tutorial to one newer or just skip this detail and continue :D
For expo login try run this two commands and try again:
npm cache clean --force
npm install -g npm#latest --force
I'm running this on ios. I followed the steps here and was able to get the "Montserrat-SemiBold" font to work. I tried doing the same thing with "Source Sans Pro" but I'm getting the error "Unrecognized font family".
I've spent a couple of hours trying multiple things I found online but can't get it to work.
This is my repo => RefugeApp
p.s. I'm using VSCode
I use expo-font to use custom fonts, It's easy and straight forward.
Steps to use custom fonts with expo-font on the bare react-native project.
Install and config unimodules on iOS/Android
Configuration for iOS
Configuration for Android
Install expo-font
npm i expo-font
Setup your custom fonts on your App.js
import "react-native-gesture-handler";
import React from "react";
import { Text } from "react-native";
import * as Font from "expo-font";
class App extends React.Component {
state = {
appIsReady: false,
};
async componentDidMount() {
this.prepareResources();
}
prepareResources = async () => {
await cacheAssets();
this.setState({ appIsReady: true });
};
render() {
if (!this.state.appIsReady) {
return <Text>loading...</Text>;
}
return <Text>App</Text>;
}
}
async function cacheAssets() {
const fontAssets = cacheFonts([
{ thin: require("./assets/fonts/thin.ttf") },
{ medium: require("./assets/fonts/medium.ttf") },
{ bold: require("./assets/fonts/bold.ttf") },
]);
await Promise.all([...fontAssets]);
}
function cacheFonts(fonts) {
return fonts.map((font) => Font.loadAsync(font));
}
export default App;
Use it
<Text style={{ fontFamily: "medium" }}>App</Text>
This might be helpful if anyone using react-native-unimodules and wants to config custom fonts.
1 - download all the fonts you want (make sure its terminated in .ttf example: Arial-narrow.ttf)
2 - rename it as simple as possible eg: from piazzolla-reagular=s8.ttf to piazzolla-regular.ttf
3 - create an "assets" folder on your project (you probably already have created one)
4 - create a folder named "fonts" inside your your assets folder and paste all your downloaded (and renamed) fonts inside there
5 - create a file named "react-native.config.js" inside your project and fill the inside with this code:
module.exports = {
project: {
ios: {},
android: {}, // grouped into "project"
},
assets: ["./assets/fonts/"], // stays the same
};
6 - on your console (inside your project directory) write:
npx react-native link
this will link your project...
now, to apply your fonts on your style component use the fontFamily prop, eg:
style={{color:'#999',fontFamily:'exo2-regular'}}
hope this helps everyone whos in need of a font guide.
ps: I concat this method from various website guides around web like:
https://mehrankhandev.medium.com/ultimate-guide-to-use-custom-fonts-in-react-native-77fcdf859cf4
How do I add a custom font in React Native?
https://medium.com/#alcides.bsilvaneto/installing-custom-fonts-ttf-or-otf-on-react-native-0-60-projects-e8dafbc0dff3
No credits for me.
If you were able to do it correctly for Montserrat-SemiBold I suppose that your fonts are installed correct so I will skip this step, let's go to "Unrecognized font family" problem
You need to check font name in your system, not by name of the file, you need to open font_book in Launchpad and check font that you interested in Example image
For example the name of file IMFellEnglishSC-Regular.ttf but in the system, it could be IM_FELL_English_SC with underscores _ :)
So you need to use it like fontFamily: IM_FELL_English_SC, even if filename is different
In your case seems like fontFamily: SourceSansPro-Regular should work for you check this image
For future you could use this cool package to easy link & unlink fonts it's quite cool and simple for such things like adding custom fonts -> react-native-assets
Cheers 🤸♂️☀️
How can I use this: https://www.npmjs.com/package/react-native-android-pip
I want to make a webview app can use PIP(Picture in Picture). But Idk how can I use this module in my code.
import * as React from 'react';
import { WebView } from 'react-native-webview';
import AndroidPip from 'react-native-android-pip';
export default class App extends React.Component {
render() {
return <WebView source={{ uri: '(My url)' }} style={{ marginTop: 50 }} />;
}
}
As said here (On the documentation itself), You can use as follow:
import AndroidPip from 'react-native-android-pip';
// Enter Pip mode
AndroidPip.enterPictureInPictureMode()
//Configure aspect ratio, works only on SDK version 26 and above
AndroidPip.configureAspectRatio(width, height)
// When enabled, PIP mode will be automatically entered when app is unfocused( User presses home
//, menu button etc)
AndroidPip.enableAutoPipSwitch()
AndroidPip.disableAutoPipSwitch()
You can call these functions on the click of a button, response of an API, start of a screen, and so on...
[EDIT]
Also, try using the github version of this module, as the npm version is 2 years old, and the github version is at 29 days without an update. Install it as follow:
npm install --save https://github.com/shaun-chiang/rn-android-pip
If you like there is an easier pilgrimage react-native-pip-android
I need to drop shadow option to add to buttons in the Android app.
In react, native default options (shadowColor, shadowOpacity, shadowRadius) only work with ios versions. Android only work with elevation option.
Does anyone know how to do this? I used react-native-shadow but it older on not supported to latest react native versions it got errors from SVG component even we installed it manually.
You can use the React Native Platform module to set an OS-specific style. For example:
import { Platform, StyleSheet } from 'react-native';
// your component //////
const styles = StyleSheet.create({
button: {
// cross-platform css
...Platform.select({
ios: {
shadowColor: rgba(0,0,0),
shadowOpacity: 0.5,
shadowRadius: 5
},
android: {
elevation: 5
},
}),
}
})
In react-native, you should avoid writing platform specific code.
When required to handle tasks like this - you should use an existing library or create your own.
react-native-drop-shadow is a good example of one of these cases. Or you could use a similar method to the one I have used in my app and just include the elevation and shadow styles in a single style object.
No External Library Required:
elevation: 5, // Android
shadowColor: '#030002', // Android, iOS & Web
shadowOpacity: 0.25, // iOS & Web
shadowRadius: 5 // iOS & web
Try to use below library:
https://github.com/Kishanjvaghela/react-native-cardview
It will fulfill your requirements
Having to work with an application that someone else developed and not available anymore. Pretty new to React-Native and Expo. Keep on getting this error:
fontFamily 'FontAwesome' is not a system font and has not been loaded through Expo.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 Expo.Font.loadAsync.
I googled this and got some other links about what people were encountering and how they solved it e.g.
import {Font} from 'expo' and async load it in via componentDidMount
import {FontAwesome} from '#expo/vector-icons' package
tried deleting where it was used and refreshing app
Here is an example of an Icon a previous developer returned:
<Icon name="sign-in" color={'#FFFFFF'} type="font-awesome" />;
which is being imported like this from react-native-elements:
import { Icon, Button } from 'react-native-elements'
All of these ways I tried didn't work. Tried reading up on Custom Font loading but it looks like everything is being done right to me in the repo. Any help appreciated!
I would use react-native-vector-icons to load in font-awesome.
Make sure and run rnpm link after you yarn or npm install the module.
Using
import Icon from 'react-native-vector-icons/FontAwesome';
const myIcon = (<Icon name="rocket" size={30} color="#900" />)