React Native - how to set fixed width to individual characters (number, letter, etc)
The system font in iOS is San Francisco, which has proportional numbers by default but contains an option for fixed-width (monospaced) numbers. With react-native, you have to use the fontVariant
property on your Text
component's style:
<Text style={{fontVariant: ['tabular-nums']}}>
1,234,567,890.12
</Text>
I had a hard time finding it because the name isn't explicit and not what is typically used. Here's a link to the the Text props on the RN doc: https://facebook.github.io/react-native/docs/text.html#style
Thanks to @ppeterka, I found a super easy solution to this that requires one line of code: use a monospace font.
Here is a list of some available monospace fonts that are shipped with iOS:
Courier
Courier-Bold
Courier-BoldOblique
Courier-Oblique
Courier New
CourierNewPS-BoldItalicMT
CourierNewPS-BoldMT
CourierNewPS-ItalicMT
CourierNewPSMT
Menlo-Bold
Menlo-BoldItalic
Menlo-Italic
Menlo-Regular
Although the question is tagged for iOS, in case anyone is looking for a generic solution that supports monospace text on both iOS and Android (like I was), then here's an additional resource for you!
Font selection:
react-native-training/react-native-fonts on GitHub has a good list of fonts which are on each platform. As you can see, there is no overlap between the monospace fonts which OP provided in their answer. However, Android has a font called 'monospace' which will work for this use case.
OS Conditional statement
Since react native will throw an error if a font in fontFamily does not exist, we will need to conditionally set the fontFamily based on what's available in the OS. Platform.OS
from react-native can be used to determine the device OS.
Example
// components/TextFixedWidth.js
import React from 'react'
import { Platform, Text } from 'react-native'
export default function TextFixedWidth ({ children }) {
const fontFamily = Platform.OS === 'ios' ? 'Courier' : 'monospace'
return (
<Text style={{fontFamily}}>{ children }</Text>
)
}
Then
// in a render method somewhere in the app
<TextFixedWidth>
Any monospace text you want!
</TextFixedWidth>
I hope this is helpful :)