7

I managed to load custom font on my react-native expo app following the official documentation:

const App = () => {
  let [fontsLoaded] = useFonts({
    'Lato-Regular': require('../assets/fonts/Lato-Regular.ttf'),
    'Lato-Bold': require('../assets/fonts/Lato-Bold.ttf'),
    'Poppins-Light': require('../assets/fonts/Poppins-Light.ttf'),
    'Poppins-Bold': require('../assets/fonts/Poppins-Bold.ttf'),
  });

So I can use it with the component style:

<Text style={{
  fontFamily: 'Lato-Bold'
}}>Home page.</Text>

But I would like to use it like this:

<Text style={{
  fontFamily: 'Lato',
  fontWeight: 'bold',
}}>Home page.</Text>

This works for system fonts, but not with custom fonts.

How can I deal with it?

Soullivaneuh
  • 3,553
  • 3
  • 37
  • 71
  • Does this answer your question? [How to set default font family in React Native?](https://stackoverflow.com/questions/35255645/how-to-set-default-font-family-in-react-native) – OriHero Apr 04 '20 at 18:22
  • Not really, as it does not explain how to deal with fontWeight properly. – Soullivaneuh Apr 06 '20 at 13:28

1 Answers1

8

You have to use custom component and extract the font weight from it. That's how it looks like

import React from 'react';
import { View, Text as RnText, StyleSheet } from 'react-native';

const Text = ({ style, children, ...rest }) => {
  let baseStyle = styles.medium;

  // Multiple styles may be provided.
  (Array.isArray(style) ? style : [style]).forEach((style) => {
    if (style && style.fontWeight) {
      baseStyle = style.fontWeight === 'bold' ? styles.bold : styles.medium;
    }
  });

  // We need to force fontWeight to match the right font family.
  return <RnText style={[baseStyle, style, { fontWeight: 'normal' }]} {...rest}>{children}</RnText>;
};

const styles = StyleSheet.create({
  bold: {
    fontFamily: 'Lato-Bold',
  },
  light: {
    fontFamily: 'Lato-Light',
  },
  medium: {
    fontFamily: 'Lato-Black',
  },
});

export default Text;
Soullivaneuh
  • 3,553
  • 3
  • 37
  • 71
OriHero
  • 1,168
  • 1
  • 10
  • 24
  • Thanks! This is working only if you delete the style.fontWeight property after your condition match. Can you please approve my suggestion so I can accept your answer? – Soullivaneuh Apr 06 '20 at 13:47
  • Actually after you set fontFamily font weight does not play a role! This was my production code and have been working pretty good! – OriHero Apr 06 '20 at 15:16
  • I agree. But if I keep it on the style var, it fallback to the default font family, not the one I set. – Soullivaneuh Apr 06 '20 at 15:37
  • Should we be using `StyleSheet.flatten` here, instead of the line starting `(Array.isArray(style)...`? – Chrispher Apr 28 '23 at 09:33