Dynamic fontFamily in FontList Item

I’m using the FlatList to show all the default fonts available on Android for React Native.
But I want to change the font family dynamically to actually look like that font.
This will get a lot more interesting on iOS that has over 100 or when I start adding custom fonts…
but to start I just went with the 10 Android fonts that default out of the box. I can hard code it and they all look the same, but when I feed it the variable I called fontJB it doesn’t even pick it up. I tried wrapping it in a separate bracket like the title but that breaks the whole page and it doesn’t even render…



const DATA = [
  {
    id: '01',
    title: 'normal',
    fontJB: 'normal',
  },
  {
    id: '02',
    title: 'notoserif',
    fontJB: 'notoserif',
  },
  {
    id: '03',
    title: 'sans-serif',
    fontJB: 'sans-serif',
  },
  {
    id: '04',
    title: 'sans-serif-light',
    fontJB: 'sans-serif-light',
  },
  {
    id: '05',
    title: 'sans-serif-thin',
    fontJB: 'sans-serif-thin',
  },
  {
    id: '06',
    title: 'sans-serif-condensed',
    fontJB: 'sans-serif-condensed',
  },
  {
    id: '07',
    title: 'sans-serif-medium',
    fontJB: 'sans-serif-medium',
  },
  {
    id: '08',
    title: 'serif',
    fontJB: 'serif',
  },
  {
    id: '09',
    title: 'Roboto',
    fontJB: 'Roboto',
  },
  {
    id: '10',
    title: 'monospace',
    fontJB: 'monospace',
  },
];

const Item = ({ title, fontJB }) => (
  <View style={styles.item}>
    <Text style={{ fontSize: 20, fontFamily: 'Roboto' }}>{title}</Text>
  </View>
);

const FontList = () => {
  const renderItem = ({ item }) => (
    <Item title={item.title} />
  );

fontFamily

fontSize

  {
    id: '09',
    title: 'Roboto',
    fontJB: 'Roboto',
  },
  {
    id: '10',
    title: 'monospace',
    fontJB: 'monospace',
  },
];

const Item = ({ title, fontJB }) => (
  <View style={styles.item}>
    <Text style={{ fontSize: 20, fontFamily: fontJB }}>{title}</Text>
  </View>
);

While setting it in the Item, I was failing to pass it into the FontList, it’s working now.

const Item = ({ title, fontJB }) => (
  <View style={styles.item}>
    <Text style={{ fontSize: 20, fontFamily: fontJB }}>{title}</Text>
  </View>
);

const FontList = () => {
  const renderItem = ({ item }) => (
    <Item title={item.title} fontJB={item.fontJB} />
  );

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={DATA}
        renderItem={renderItem}
        keyExtractor={item => item.id}
      />
    </SafeAreaView>
  );
};
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.