How to Use Text in React Native: Simple Guide
In React Native, use the
Text component to display text on the screen. Wrap your text inside <Text> tags within your component's return statement to render it.Syntax
The Text component is used to display text in React Native. You write it as <Text>Your text here</Text>. You can also style it using the style prop.
javascript
import React from 'react'; import { Text } from 'react-native'; export default function MyText() { return <Text style={{ fontSize: 16, color: 'black' }}>Hello, React Native!</Text>; }
Output
Displays the text 'Hello, React Native!' in black color with font size 16 on the screen.
Example
This example shows a simple React Native app displaying a greeting message using the Text component with basic styling.
javascript
import React from 'react'; import { SafeAreaView, Text, StyleSheet } from 'react-native'; export default function App() { return ( <SafeAreaView style={styles.container}> <Text style={styles.text}>Welcome to React Native!</Text> </SafeAreaView> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#f0f0f0' }, text: { fontSize: 20, color: '#333' } });
Output
Centered text 'Welcome to React Native!' in dark gray on a light gray background.
Common Pitfalls
One common mistake is forgetting to import Text from react-native. Another is trying to use HTML tags inside Text, which React Native does not support. Also, nesting Text components incorrectly can cause layout issues.
javascript
/* Wrong: Missing import */ export default function Wrong() { return <Text>Missing import causes error</Text>; } /* Right: Correct import */ import React from 'react'; import { Text } from 'react-native'; export default function Right() { return <Text>Properly imported Text component</Text>; }
Output
The wrong example causes an error; the right example displays text correctly.
Quick Reference
- Import: Always import
Textfromreact-native. - Usage: Wrap text inside
<Text>tags. - Styling: Use the
styleprop with a style object or stylesheet. - Nesting: You can nest
Textcomponents for different styles.
Key Takeaways
Use the
Text component to display text in React Native apps.Always import
Text from react-native before using it.Style text using the
style prop with JavaScript objects or StyleSheet.Avoid using HTML tags inside
Text; React Native uses its own components.You can nest
Text components to apply different styles within the same block.