30 Days of React Native
This post is part of the series 30 Days of React Native.
In this series, we're starting from the very basics and walk through everything you need to know to get started with React Native. If you've ever wanted to learn React Native, this is the place to start!
The Text component is one of the most common React Native components — we use it whenever we need to display text in our app.
Unlike with React on the web, we can't just put text content directly inside any component. For example, this code won't run:
Instead, we need to wrap all of our text within a
<View> <Text>My text</Text> </View>
We've previously covered how we can use the style prop to style components in general. Here we'll cover some of the common ways we can style Text components specifically.
Text components can use all of the same style properties as View components, plus an additional set of
Text-specific properties. Here are a few of the most common
- fontFamily: The name of the font family, e.g. "Helvetica".
- fontSize: The size to draw the font, in pixels.
- fontWeight: This thickness of the font. One of: 'normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'.
- lineHeight: The height of each line of text that includes the space above and below the text itself.
- textAlign: The alignment of the text drawn within the
Textcomponent. One of: 'auto', 'left', 'right', 'center', 'justify'.
- color: The text color.
In the following example, we'll set each of these properties, along with a few we've already used to style our View components:
Text components automatically grow horizontally to fit the text content drawn within. If the
Text component can't grow horizontally within its parent anymore, it will then wrap the text content to the next line and grow vertically. However, we can override this behavior by specifying the dimensions of the component ourselves.
In this example, we set the width of the
Text to 200 explicitly, which affects where it wraps to the next line:
Note that textAlign affects the alignment of the text content drawn within the
Text component, but not the component itself. If we want to align the
Text component in the horizontal center of the screen, we would set the alignItems style property on the parent View.
Text components are similar to "block" elements on the web — if we use multiple
Text elements within the same parent, they will stack on top of each other: