String concatenation in React Native

By , last updated February 3, 2020

React Native is a JavaScript-based framework. Strings and string operations will be much like in JavaScript.

To create a simple string in React Native and save it in a variable use let or const and single quotes.

const hello = 'Hello, ';
const world = 'World!';

Use the + operator to concatenate two string variables in React Native:

const helloWorld = hello + world;

Another version with a hardcoded string:

const helloWorld2 = hello + 'World!';

Both code samples will print “Hello, World!” on one line:

String concatenation with a newline in React Native:

const helloWorld = hello + '\n' + world;

In ES6 (ES2015) you can use template literals instead, which are more readable and more powerful than simple string concatenation.

You will need to use special quotation marks called back-ticks (“) with template literals:

const helloWorld = `${hello}${world}`;
const helloWorld2 = `Hello! ${world}`;

In order to perform string concatenation with newline or multiline strings place each new string on a new line in the editor or use a newline HTML markup \n.

const helloWorld = `${hello}
    ${world}`;
const helloWorld2 = 'Hello!\n' + `${world}`;
const helloWorld3 = `${hello}` + ' \n ' + `${world}`;
const helloWorld4 = `${hello} \n ${world}`;

The expression in curly brackets after the dollar-sign ${expression} is called a placeholder and is a powerful tool in ES6 allowing to parse a string as a function.

Here’s the whole code of the main JavaScript file (App.js or main.js) in our simple React Native application:

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

export default class App extends React.Component {
  render() {
    const hello = 'Hello, ';
    const world = 'World!';
    const helloWorld = `${hello}
    ${world}`;
    const helloWorld2 = 'Hello!\n' + `${world}`;
    const helloWorld3 = `${hello}` + '\n' + `${world}`;
    const helloWorld4 = `${hello} \n ${world}`;

    return (
      <View style={styles.container}>
        <Text>{helloWorld}</Text>
        <Text>{helloWorld2}</Text>
        <Text>{helloWorld3}</Text>
        <Text>{helloWorld4}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});