How can I insert a line break into a <Text> component in React Native?

JavascriptTextReact NativeNewline

Javascript Problem Overview


I want to insert a new line (like \r\n, <br />) in a Text component in React Native.

If I have:

<text>
<br />
Hi~<br />
this is a test message.<br />
</text>

Then React Native renders Hi~ this is a test message.

Is it possible render text to add a new line like so:

Hi~
this is a test message.

Javascript Solutions


Solution 1 - Javascript

This should do it:

<Text>
Hi~{"\n"}
this is a test message.
</Text>

Solution 2 - Javascript

You can also do:

<Text>{`
Hi~
this is a test message.
`}</Text>

Easier in my opinion, because you don't have to insert stuff within the string; just wrap it once and it keeps all your line-breaks.

Solution 3 - Javascript

Use:

<Text>{`Hi,\nCurtis!`}</Text>

Result:

> Hi, > > Curtis!

Solution 4 - Javascript

This worked for me

<Text>{`Hi~\nthis is a test message.`}</Text>

(react-native 0.41.0)

Solution 5 - Javascript

If at all you are displaying data from state variables, use this.

<Text>{this.state.user.bio.replace('<br/>', '\n')}</Text>

Solution 6 - Javascript

You can use {'\n'} as line breaks. Hi~ {'\n'} this is a test message.

Solution 7 - Javascript

Solution 1:

<Text>
Hi~{"\n"}
this is a test message.
</Text>

Solution 2:

 <Text>{`
  line 1
  line 2
 `}</Text>

Solution 3:

Here was my solution of handling multiple <br/> tags:

<Text style={{ whiteSpace: "pre-line" }}>
    {"Hi<br/> this is a test message.".split("<br/>").join("\n")}
</Text>

Solution 4:

use maxWidth for auto line break

<Text style={{ maxWidth:200}}>this is a test message. this is a test message</Text>

Solution 8 - Javascript

EDIT :

if you use Template Literals (see within the <Text> element) , you can also just add the line breaks like this:

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

export default class extends Component {

 (...)

 render(){
  return (
    <View>
      <Text>{`
        1. line 1
        2. line 2
        3. line 3
      `}</Text>
    </View>
  );
 }
}

Solution 9 - Javascript

https://stackoverflow.com/a/44845810/10480776 @Edison D'souza's answer was exactly what I was looking for. However, it was only replacing the first occurrence of the string. Here was my solution to handling multiple <br/> tags:

<Typography style={{ whiteSpace: "pre-line" }}>
    {shortDescription.split("<br/>").join("\n")}
</Typography>

Sorry, I couldn't comment on his post due to the reputation score limitation.

Solution 10 - Javascript

I needed a one-line solution branching in a ternary operator to keep my code nicely indented.

{foo ? `First line of text\nSecond line of text` : `Single line of text`}

Sublime syntax highlighting helps highlight the line-break character:

Sublime syntax highlight

Solution 11 - Javascript

You can try using like this

<text>{`${val}\n`}</text>

Solution 12 - Javascript

this is a nice question , you can do this in multiple ways First

<View>
    <Text>
        Hi this is first line  {\n}  hi this is second line 
    </Text>
</View>

which means you can use {\n} backslash n to break the line

Second

<View>
     <Text>
         Hi this is first line
     </Text>
     <View>
         <Text>
             hi this is second line 
         </Text>
     </View>
</View>

which means you can use another <View> component inside first <View> and wrap it around <Text> component

Happy Coding

Solution 13 - Javascript

You can also just add it as a constant in your render method so its easy to reuse:

  render() {
    const br = `\n`;
     return (
        <Text>Capital Street{br}Cambridge{br}CB11 5XE{br}United Kingdom</Text>
     )  
  }

Solution 14 - Javascript

You can use `` like this:

<Text>{`Hi~
this is a test message.`}</Text>

Solution 15 - Javascript

You can do it as follows:

{'Create\nYour Account'}

Solution 16 - Javascript

Just put {'\n'} within the Text tag

<Text>

   Hello {'\n'}

   World!

</Text>

Solution 17 - Javascript

One of the cleanest and most flexible way would be using Template Literals.

An advantage of using this is, if you want to display the content of string variable in the text body, it is cleaner and straight forward.

(Please note the usage of backtick characters)

const customMessage = 'This is a test message';
<Text>
{`
  Hi~
  ${customMessage}
`}
</Text>

Would result in

Hi~
This is a test message

Solution 18 - Javascript

Here is a solution for React (not React Native) using TypeScript.

The same concept can be applied to React Native

import React from 'react';

type Props = {
  children: string;
  Wrapper?: any;
}

/**
 * Automatically break lines for text
 *
 * Avoids relying on <br /> for every line break
 *
 * @example
 * <Text>
 *   {`
 *     First line
 *
 *     Another line, which will respect line break
 *  `}
 * </Text>
 * @param props
 */
export const Text: React.FunctionComponent<Props> = (props) => {
  const { children, Wrapper = 'div' } = props;

  return (
    <Wrapper style={{ whiteSpace: 'pre-line' }}>
      {children}
    </Wrapper>
  );
};

export default Text;

Usage:

<Text>
  {`
    This page uses server side rendering (SSR)

    Each page refresh (either SSR or CSR) queries the GraphQL API and displays products below:
  `}
</Text>

Displays: enter image description here

Solution 19 - Javascript

Simple use backticks (ES 6 feature)

SOLUTION 1

const Message = 'This is a message';

<Text>
{`
  Hi~
  ${Message}
`}
</Text>

SOLUTION 2 Add "\n" in Text

<Text>
Hi~{"\n"}
This is a message.
</Text>

Solution 20 - Javascript

do this:

<Text>

 { "Hi~ \n this is a test message." }

<Text/>

Solution 21 - Javascript

If you're getting your data from a state variable or props, the Text component has a style prop with minWidth, maxWidth.

example

const {height,width} = Dimensions.get('screen');

const string = `This is the description coming from the state variable, It may long thank this` 

<Text style={{ maxWidth:width/2}}>{string}</Text>

This will display text 50% width of your screen

Solution 22 - Javascript

Just use {"\n"} where you want to break the line

Solution 23 - Javascript

Another way to insert <br> between text lines that are defined in an array:

import react, { Fragment } from 'react';

const lines = [
  'One line',
  'Another line',
];

const textContent =
  lines.reduce(items, line, index) => {
    if (index > 0) {
      items.push(<br key={'br-'+index}/>);
    }
    items.push(<Fragment key={'item-'+index}>{line}</Fragment>);
    return items;
  }, []);

Then the text can be used as variable:

<Text>{textContent}</Text>

If not available, Fragment can be defined this way:

const Fragment = (props) => props.children;

Solution 24 - Javascript

This code works on my environment. (react-native 0.63.4)

const charChangeLine = `
`
// const charChangeLine = "\n" // or it is ok

const textWithChangeLine = "abc\ndef"

<Text>{textWithChangeLine.replace('¥n', charChangeLine)}</Text>

Result

abc
def

Solution 25 - Javascript

In case anyone is looking for a solution where you want to have a new line for each string in an array you could do something like this:

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


export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      description: ['Line 1', 'Line 2', 'Line 3'],
    };
  }

  render() {
    // Separate each string with a new line
    let description = this.state.description.join('\n\n');

    let descriptionElement = (
      <Text>{description}</Text>
    );

    return (
      <View style={{marginTop: 50}}>
        {descriptionElement}
      </View>
    );
  }
}

See snack for a live example: https://snack.expo.io/@cmacdonnacha/react-native-new-break-line-example

Solution 26 - Javascript

sometimes I write like this:

<Text>
  You have {" "}
  {remaining}$ {" "}
  from{" "}
  {total}$
<Text>

(as it looks more clear for myself)

Solution 27 - Javascript

Best way use list like UL or OL and do some styling like make list style none and you can use <li> dhdhdhhd </li>

Solution 28 - Javascript

I know this is quite old but I came up with a solution for automatically breaking lines which allows you to pass in the text in the usual way (no trickery)

I created the following component

import React, {} from "react";
import {Text} from "react-native";

function MultiLineText({children,  ...otherProps}) {

const splits = children.split("\\n")
console.log(splits);
const items = []
for (let s of splits){
  items.push(s)
  items.push("\n")
}

  return (
    <Text {...otherProps}>{items}</Text>
  );
}


export default MultiLineText;

Then you can just use it like so..

<MultiLineText style={styles.text}>This is the first line\nThis is teh second line</MultiLineText>

Solution 29 - Javascript

This should do the trick !

<Text style={{styles.text}}>{`Hi~\nthis is a test message.`}</Text>

Solution 30 - Javascript

Use \n in text and css white-space: pre-wrap;

Solution 31 - Javascript

<Text>
Hi~{"\n"}
this is a test message.
</Text>

Solution 32 - Javascript

Why work so hard? it's 2020, create a component to handle this type of issues

    export class AppTextMultiLine extends React.PureComponent {
    render() {
    const textArray = this.props.value.split('\n');
return (
        <View>
            {textArray.map((value) => {
               return <AppText>{value}</AppText>;
            })}
        </View>
    )
}}

Solution 33 - Javascript

React won't like you putting HTML <br /> in where it's expecting text, and \ns aren't always rendered unless in a <pre> tag.

Perhaps wrap each line-breaked string (paragraph) in a <p> tag like this:

{text.split("\n").map((line, idx) => <p key={idx}>{line}</p>)}

Don't forget the key if you're iterating React components.

Solution 34 - Javascript

2021, this works for a REACT state Value (you have to add empty divs, just like a return statement)

this.setState({form: (<> line 1 <br /> line 2 </>) })

Solution 35 - Javascript

I used p Tag for new line. so here i pasted code .that will helpfu for anyone.

const new2DArr =  associativeArr.map((crntVal )=>{
          return <p > Id :  {crntVal.id} City Name : {crntVal.cityName} </p>;
     });

Solution 36 - Javascript

Hey just put them like this it works for me !

>

>

> {" "} > Hello {"\n"} >

> {"\n"} >

I am here

>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCurtisView Question on Stackoverflow
Solution 1 - JavascriptChris GheneaView Answer on Stackoverflow
Solution 2 - JavascriptVenryxView Answer on Stackoverflow
Solution 3 - JavascriptCOdekView Answer on Stackoverflow
Solution 4 - JavascriptOlivierView Answer on Stackoverflow
Solution 5 - JavascriptEdison D'souzaView Answer on Stackoverflow
Solution 6 - JavascriptVijay SuryawanshiView Answer on Stackoverflow
Solution 7 - JavascriptMuhammad NumanView Answer on Stackoverflow
Solution 8 - JavascriptTelmo DiasView Answer on Stackoverflow
Solution 9 - Javascriptilike2breakthngsView Answer on Stackoverflow
Solution 10 - JavascriptBeau SmithView Answer on Stackoverflow
Solution 11 - JavascriptPankaj AgarwalView Answer on Stackoverflow
Solution 12 - JavascriptShahmir KhanView Answer on Stackoverflow
Solution 13 - JavascriptTim JView Answer on Stackoverflow
Solution 14 - JavascriptIdanView Answer on Stackoverflow
Solution 15 - JavascriptHimanshu AhujaView Answer on Stackoverflow
Solution 16 - JavascriptCurious96View Answer on Stackoverflow
Solution 17 - JavascriptAkhil BalakrishnanView Answer on Stackoverflow
Solution 18 - JavascriptVadorequestView Answer on Stackoverflow
Solution 19 - Javascriptuser13018007View Answer on Stackoverflow
Solution 20 - JavascriptMahdi EslamiView Answer on Stackoverflow
Solution 21 - JavascriptabduljeleelngView Answer on Stackoverflow
Solution 22 - JavascriptM.Hassam YahyaView Answer on Stackoverflow
Solution 23 - JavascriptMax OriolaView Answer on Stackoverflow
Solution 24 - JavascriptasukiaaaView Answer on Stackoverflow
Solution 25 - JavascriptCathal Mac DonnachaView Answer on Stackoverflow
Solution 26 - JavascriptmrxrincView Answer on Stackoverflow
Solution 27 - JavascriptlodeyView Answer on Stackoverflow
Solution 28 - JavascriptCharlie MortonView Answer on Stackoverflow
Solution 29 - JavascriptMuhammad HumzaView Answer on Stackoverflow
Solution 30 - JavascriptAlexey ZavrinView Answer on Stackoverflow
Solution 31 - JavascriptIresha AmarasingheView Answer on Stackoverflow
Solution 32 - Javascriptuser3086644View Answer on Stackoverflow
Solution 33 - JavascripterrkkView Answer on Stackoverflow
Solution 34 - JavascriptRishi BhachuView Answer on Stackoverflow
Solution 35 - Javascriptpankaj kumarView Answer on Stackoverflow
Solution 36 - JavascriptFarbod AprinView Answer on Stackoverflow