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

40

643

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.
Rage answered 9/9, 2015 at 1:29 Comment(2)
You can use \n where you want to break the line.Attorneyatlaw
no \n will not work. i used. i would suggest use html tags for render and use css or simply <p> text </p>. you can use.Herzen
M
1081

This should do it:

<Text>
Hi~{"\n"}
this is a test message.
</Text>
Mayda answered 9/9, 2015 at 12:55 Comment(12)
Is there a way to do it with string from variable so I could use: <Text>{content}</Text> ?Jocko
\n is a line breakMayda
Thanks for this. I ended up making a line break component for quick access var Br = React.createClass({ render() { return ( <Text> {"\n"}{"\n"} </Text> ) } })Imre
This ended up line breaking my entire screen (all components on the same level). :SBobo
Isn't there any tag like <br>? What if we want to give a line break b/w two tags?Pongid
is there anything to do linebreak based on text no count ?Xenophobe
What if the text is in a string variable? <Text>{comments}</Text> We cannot use the {\n} logic there. Then how?Syllogistic
If the text comes from a prop, make sure you pass it like this: <Component text={"Line1\nLine2"} /> instead of <Component text="Line1\nLine2" /> (notice the added curly braces)Mechanotherapy
Using variable inside <Text>{content}</Text> with newline character will work normally. If that's not working it is due to \\n as newline character is escaped with the extra \. In that case use <Text>{content.replace(/[^\]\\n/g, '\n')}</Text>.Mopboard
None of the suggestions on this page worked for me. But I found something that worked elsewhere: forum.freecodecamp.org/t/newline-in-react-string-solved/68484 (basically inserting a symbol ('\n', for example) in the string and then in the rendering component splitting the string at each symbol and mapping the substrings)Infinitude
This worked for me: {"\n"} inside tag TextFlurried
If you need to pass components inside the text, such as icons, you can do the following: <Component text={<>Some text then an icon <Ionicons name="ios-information-circle" /> then a line-break{"\n"}Then the end text.</>}. Note the <></>, which can also be replaced with other components that can go inside a <Text> component.Crackleware
T
182

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.

Taiwan answered 21/11, 2016 at 6:31 Comment(9)
this is cleanest solution so far, together with white-space: pre-line;Sinistrality
@Tomasz: I think there is no white-space or whiteSpace: -Stylesheet for <Text>-Tag in react-native - or am I wrong?Debris
Template literals are clean and neat compare to accepted answerMotmot
I guess the white-space style is supposed to remove intendation spaces, right? If yes, I desperately need it, otherwise string literals get super ugly...Courbet
@Xerus You can just use a text post-processor to remove the indentation, as seen here: gist.github.com/Venryx/84cce3413b1f7ae75b3140dd128f944cTaiwan
Great for bodies of text. You can't style individual words though.Piwowar
this is cleanest solution so far, but it needs white-space: pre-wrap;, not white-space: pre-line;, in order to keep indentation correct.Chong
agree, style of "white-space: pre-line" is the most clean solution, it works, and that's actually how html works.Alisun
I agree that this is the cleanest solution but it does not work on React Native which is what the question is asking. There is not a direct replacement for white-space on native and it doesn't work in all the cases.Borderline
F
79

Use:

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

Result:

Hi,

Curtis!

Forepeak answered 17/5, 2018 at 9:46 Comment(3)
This seems not to be working when the message is a string variable: <Text>{message}</Text>Syllogistic
You can use function like this: splitLine = message => { ... } and RegExp in it, then <Text>{this.splitLine(message)}</Text>Forepeak
If the passed text is empty the Text element will display "undefined".Aenea
S
67

Solution 1:

<Text>
  line 1{"\n"}
  line 2
</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>
Saffier answered 4/10, 2021 at 13:33 Comment(1)
my up vote is for white-space: pre-line in solution 3 which allows you pass in a variable with \n style breaks and get them renderedBelgravia
S
24

This worked for me

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

(react-native 0.41.0)

Surrebuttal answered 13/2, 2017 at 13:47 Comment(0)
P
23

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

<Text>{this.state.user.bio.replace('<br/>', '\n')}</Text>
Praefect answered 30/6, 2017 at 11:51 Comment(0)
H
22

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

Hospitalize answered 17/11, 2017 at 6:16 Comment(0)
G
14

https://mcmap.net/q/63901/-how-can-i-insert-a-line-break-into-a-lt-text-gt-component-in-react-native @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.

Gash answered 3/5, 2020 at 2:37 Comment(1)
This solution worked for me! Inside of the Typography I had this: {"${t('RateOptions.Details', { defaultValue: 'Rate info' })}".split('<br/>').join('\n')} Note the double quotes are supposed to be backticksAlkyl
M
12

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>
  );
 }
}
Mellon answered 28/11, 2018 at 1:17 Comment(5)
This has nothing to do with styled-components and will work no matter if you use them or not.Algorithm
I think the comment above is saying that styled-components isn't what is providing the line-break, so there's no reason to use or mention it as the solution. It's the template literal that's providing the line break. Also, suggesting to install a new package to solve a simple problem is not necessary.Miasma
This answer suggests adding styled-components but it's actually the template literal that provides the break, therefore styled-components does not participate in the solution at all. I should have made this more clear in my comment, sorry. Anyway it's hard to find a "constructive way to improve the answer" if it misses the point. If you're still looking for one though, then it would say something about removing styled-components from it leaving only template string literal, which are actually the solution (one of possible).Algorithm
Thank you for the cooperation, what I meant was not that I don't know how to update the answer, but that instead of writing comments like that does not really help anyone, and if one thing stackoverflow teaches us is that cooperation makes wonders, therefore it's really appreciated if everybody replies in a constructive way. But honestly thanks for your contributions.Mellon
This suggestion helped to solve my case! BravoMons
B
11

Use {"\n"} where you want the line break

Bloemfontein answered 6/9, 2019 at 11:29 Comment(0)
B
7

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

Baca answered 31/3, 2017 at 22:12 Comment(0)
B
6

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

Bello answered 29/12, 2020 at 16:25 Comment(0)
U
5

You can try using like this

<text>{`${val}\n`}</text>
Unstriped answered 29/8, 2018 at 11:26 Comment(0)
W
3

You can use `` like this:

<Text>{`Hi~
this is a test message.`}</Text>
Wastebasket answered 6/12, 2018 at 16:15 Comment(0)
E
3

You can do it as follows:

{'Create\nYour Account'}

Example answered 14/3, 2019 at 9:27 Comment(1)
It worked form as well here <Header headerText={'Muhammad\n Tayyab\n Rana'} subHeadline="Web Developer and Designer" />Adiathermancy
T
3

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>
     )  
  }
Toreutic answered 27/6, 2019 at 11:3 Comment(0)
H
3

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

<Text>

   Hello {'\n'}

   World!

</Text>
Hubbs answered 16/11, 2019 at 18:13 Comment(0)
B
3

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
Barbaric answered 27/2, 2020 at 6:42 Comment(0)
H
3

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

Histo answered 6/5, 2020 at 13:42 Comment(0)
T
3

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>
Trimming answered 11/10, 2020 at 8:49 Comment(0)
G
3

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>
Garver answered 2/5, 2022 at 16:54 Comment(0)
T
3

There are two main solutions for this.

Method 1: Just add the '\n' like below

<Text>
   First Line {'\n'} Second Line.
</Text>

Method 2: Add the line break it in the string literals, like below.

 <Text>
   `First Line  
   Second Line`.
 </Text>

For more information, please refer the below tutorial.

https://sourcefreeze.com/how-to-insert-a-line-break-into-a-text-component-in-react-native/

Triceratops answered 25/7, 2022 at 10:1 Comment(1)
Should be {`First line etc`}Extension
C
3

Y'all can try this if trying to use a variable inside an element.

<Text>{newText}</Text>

const newText= text.body.split("\n").map((item, key) => {
    return (
      <span key={key}>
        {item}
        <br />
      </span>
    );
  });
Conoscenti answered 9/12, 2022 at 6:14 Comment(0)
C
2

do this:

<Text>

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

<Text/>
Captor answered 29/12, 2020 at 8:40 Comment(0)
A
2

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

Appurtenant answered 3/2, 2021 at 12:38 Comment(0)
C
1

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

Chemisorption answered 24/7, 2018 at 14:59 Comment(2)
I don’t see whiteSpace listed as a React Native Text Style Prop. Note that this isn’t HTML.Ula
for reference this works in react js. Others for some reason not working for me.Shovelboard
N
1

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;
Narrows answered 26/2, 2020 at 12:2 Comment(0)
W
1

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
Walkon answered 8/2, 2021 at 6:0 Comment(0)
G
0

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

Gagman answered 15/5, 2019 at 20:37 Comment(0)
F
0

sometimes I write like this:

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

(as it looks more clear for myself)

Forcefeed answered 9/4, 2021 at 22:39 Comment(0)
N
0

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

Nuzzle answered 6/3, 2022 at 3:37 Comment(0)
B
0

I also really liked solution #3 from this answer, but I was getting a Console Warning: Failed prop type: Invalid props.style key 'whitespace'

However, just passing my text inside symbols {``} with \n seems enough without any changes to the text style. So for the original question the best answer IMHO would be:

{`Hi~\nthis is a test message.`}
Biernat answered 24/1, 2024 at 1:28 Comment(0)
E
-1

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>
    )
}}
Electrograph answered 21/9, 2020 at 12:5 Comment(1)
Overhead, Just use template literalsNels
L
-1

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.

Lias answered 7/12, 2020 at 15:41 Comment(0)
J
-2
<Text>
Hi~{"\n"}
this is a test message.
</Text>
Jammiejammin answered 1/7, 2020 at 4:59 Comment(2)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Edema
\n means new line.Jammiejammin
H
-2

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>;
     });
Herzen answered 16/3, 2021 at 9:53 Comment(0)
P
-2

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 </>) })

Paraclete answered 11/6, 2021 at 7:2 Comment(1)
The question is concerned with React Native as opposed to plain React. In React Native we do not have<br /> tags available.Kaplan
E
-2

This should do the trick !

<Text style={{styles.text}}>{`Hi~\nthis is a test message.`}</Text>
Euplastic answered 9/5, 2022 at 7:8 Comment(0)
I
-3

Hey just put them like this it works for me !

   <div>
       <p style={{ fontWeight: "bold", whitespace: "pre-wrap" }}>
         {" "}
         Hello {"\n"}
       </p>
         {"\n"}
       <p>I am here</p>
   </div>
Insnare answered 2/3, 2021 at 7:23 Comment(0)
T
-3

An empty View does the trick

<Text> some text </Text>
<View />
<Text> another line </Text>
Tosch answered 1/5, 2023 at 14:14 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.