Ora

How do I add a string in React Native?

Published in React Native Strings 3 mins read

In React Native, you primarily display strings using the <Text> component and add or combine strings through various JavaScript methods, with template literals offering the most modern and readable approach.

Displaying Static Strings

To display any string in React Native, you must enclose it within a <Text> component. This component is specifically designed to render text on the screen.

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

const App = () => {
  return (
    <View style={styles.container}>
      <Text style={styles.baseText}>Hello, React Native!</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  baseText: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#333',
  },
});

export default App;

Combining Strings (Concatenation)

You often need to combine static text with dynamic data (variables) or other strings.

Using the + Operator

The traditional JavaScript way to concatenate strings is by using the + operator. This works well for simple combinations.

import React from 'react';
import { View, Text } => {
  const userName = "Alice";
  const message = "Welcome, " + userName + "!";

  return (
    <View>
      <Text>{message}</Text>
      <Text>Your score is: " + 100 + "."</Text>
    </View>
  );
};

export default MyComponent;

Pros:

  • Familiar to JavaScript developers.

Cons:

  • Can become verbose and less readable with many variables or complex structures.
  • Requires explicit conversion for non-string types (though JavaScript often handles this implicitly for +).

Using Template Literals for String Interpolation

For a more elegant and readable way to add strings, especially when incorporating variables, React Native (and modern JavaScript) highly recommends using template literals.

Template literals are defined using backticks (`) instead of single or double quotes. Inside a template literal, you can directly embed JavaScript expressions, including variables, using the syntax ${expression}. This process is called string interpolation.

import React from 'react';
import { View, Text } from 'react-native';

const MyComponent = () => {
  const firstName = "John";
  const lastName = "Doe";
  const age = 30;

  // Using template literal for readability
  const greeting = `Hello, ${firstName} ${lastName}!`;
  const userDetails = `You are ${age} years old.`;
  const complexMessage = `The user's full name is ${firstName} ${lastName} and they are interested in learning more about React Native.`;

  return (
    <View>
      <Text>{greeting}</Text>
      <Text>{userDetails}</Text>
      <Text>{complexMessage}</Text>
      {/* You can also embed expressions directly */}
      <Text>{`Next year, you will be ${age + 1} years old.`}</Text>
    </View>
  );
};

export default MyComponent;

Pros:

  • Enhanced Readability: The string's structure is clearer, as variables are embedded directly.
  • Simplified Concatenation: Avoids the need for explicit + operators, especially with multiple variables.
  • Multi-line Strings: Template literals can span multiple lines without special characters, making it easier to format long texts.
  • Expression Embedding: You can embed any JavaScript expression, not just variables (e.g., age + 1, function calls).

Practical Considerations for Adding Strings

  • Always Use <Text>: Remember that any string content you want to render visually on the screen in React Native must be wrapped within a <Text> component.
  • Styling: Apply styles directly to the <Text> component using the style prop.
  • Nested <Text> Components: For complex styling (e.g., making part of a sentence bold), you can nest <Text> components.
    <Text>
      This is a <Text style={{ fontWeight: 'bold' }}>bold word</Text> in a sentence.
    </Text>
  • Internationalization (i18n): For apps targeting multiple languages, avoid hardcoding strings. Instead, use an i18n library (like react-i18next) to manage translations and dynamically insert strings.
  • Accessibility: Ensure your string content is clear and concise for screen readers.

Comparison of String Combination Methods

Method Syntax Readability for Complex Strings Multi-line Support Best Use Case
+ Operator "Hello, " + name + "!" Low No (needs \n) Simple concatenation of 2-3 parts
Template Literal `Hello, ${name}!` High Yes Most scenarios, especially with variables or multiline

For further details on rendering text in React Native, refer to the official documentation on the Text component.