DEV Community

Cover image for Fixed Width Text in React Native
Spencer Carli
Spencer Carli

Posted on • Originally published at reactnativeschool.com

3 2

Fixed Width Text in React Native

Despite working on React Native daily for 7 years, I'm still constantly learning new things about it. Recently it was the fontVariant style prop on a Text component.

This post was published a week ago on React Native School. Be sure to visit for the latest tips, tricks and tutorials on React Native!

I was working a multi-theme stop watch app in React Native (it's open source!) and ran into an issue where the width of each number was different.

Normally this is not a problem but when you are changing the numbers every millisecond it looks quite hectic.

Demo of Problem

To fix this is a simple one liner:

When styling the text, add fontVariant: ["tabular-nums"]. This will make the text a fixed width so your layout stays fixed.

Code from the example app:

// ...

const styles = StyleSheet.create({
  // ...
  timeText: {
    fontSize: 60,
    fontWeight: "300",
    marginTop: 100,
    fontVariant: ["tabular-nums"], // fixed width character
  },
})

export default StopWatch
Enter fullscreen mode Exit fullscreen mode

Demo of Solution

MDN has a good resource through which you can learn more about the font-variant CSS property.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (1)

Collapse
 
yongchanghe profile image
Yongchang He

Thank you for sharing this!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more