React native example to create Text with different colors or multicolored Text

Introduction :

In this tutorial, I will show you how to add a different color to one part of a Text in React Native. Normally, we create one Text component with only one color. But sometimes we might require to highlight one part of a Text component. This is really easy and in this post, we will learn how to do that with example.

React native example program :

The idea is to put one Text component inside another component. For example :

<Text style={styles.paragraph}>
  The quick brown fox jumps over the{" "}
  <Text style={styles.highlight}>lazy dog</Text>
</Text>

Here, we are adding two different styles to both texts. If you add different colors, for example black for the outer text and red for the inner text, it will look like as below :

React native different color or multi colored text

Below is the complete example :

import * as React from "react";
import { Text, View, StyleSheet } from "react-native";

export default function App() {
  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>
        The quick brown fox jumps over the{" "}
        <Text style={styles.highlight}>lazy dog</Text>
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    paddingTop: 20,
    backgroundColor: "#ecf0f1",
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: "bold",
    textAlign: "center",
    color: "black",
  },
  highlight: {
    color: "red",
  },
});

Here, paragraph styling is used for the outer Text and highlight styling is used for the inner Text i.e. the text to highlight. We are using ’red’ color to highlight the text.

Highlight one part of the text dynamically :

We can highlight one part of a text or sub string of a string. For that, we need the text to highlight. We can find the start and end indices of the highlight string in the main string and put it in a new Text view dynamically.

const str = 'The quick brown fox jumps over the lazy dog';
const highlight = 'lazy';

let startIndex = str.indexOf(highlight);
let endIndex = str.indexOf(highlight) + highlight.length;

return (
  <View style={styles.container}>
    <Text style={styles.paragraph}>
      {str.substring(0, startIndex)}
      <Text style={styles.highlight}>
        {str.substring(startIndex, endIndex)}
      </Text>
      {str.substring(endIndex, str.length)}
    </Text>
  </View>
);
}

str is the complete string. highlight is the sub string to highlight. We are finding the start and end index of the highlight string using the indexOf method. Finally, we are concatenating the sub string before the highlighted string, highlighted string and sub string after the highlighted string. We are using one different styling for the highlighted text. You can change the highlight string and it will highlight that part of the original string dynamically.