Black Friday Sale Upgrade Your Home →

Display and Format Text in a react-native-application

Display and Format Text in a React Native Application

Displaying text is a key component of mobile apps, so we’ll look at how to show text on the screen, and how it differs from text on the web. We’ll also format the text style to change the size, alignment, and more.

Remember

Remember that when you want to display text in a React Native app, it must be wrapped in a text tag. It cannot just be put inside of View or another component. If we wanted to add a second name here and reload, we'd get an error because the text is not wrapped in a Text component. Instead, let's duplicate what we did for the first restaurant and display our second entry.

Components are like HTML elements

HTML elements are not available in React Native, instead, apps are composed of components imported from the react-native package. Most HTML elements have a comparable React Native component, the most basic being a View component - similar to a <div> - and a Text component - similar to a <span>.

JSX
import { Text, View } from 'react-native'

The main difference between these components and their HTML equivalents is that text may only appear in a <Text /> component, not a <View />. <Text /> components may also contain other nested <Text /> components but cannot contain nested <View /> components. <View /> components may contain other nested <View /> or <Text /> components.

JSX
<View>
<Text>hello</Text>
</View>

JSX
<View>hello</View>

| Component | Contain <View /> | Contain <Text /> | Contain text | | ---------- | ------------------ | ------------------ | ------------ | | <View /> | ✅ |✅ |❌ | | <Text /> | ❌ |✅ |✅ |

A similarity these components share with their HTML equivalents are that sibling <View /> components will stack vertically - like block level elements - and sibling <Text /> components will stack horizontally - like inline elements.

Styling

CSS style rules can be applied to components using the inline style prop. The syntax is similar to CSS on the web, however, rules are declared as a JSON object, with each rule's property being the key and value being the value.

JS
<View style={{
backgroundColor: 'green',
padding: 2
}} />

New components

🤔<View /> - used for general layout and styling.

🤔<Text /> - used for displaying and styling text.


🐦   Previous   💼   Next