454
votes

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.
30
You can use \n where you want to break the line.Sid009
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.pankaj kumar

30 Answers

847
votes

This should do it:

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

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.

48
votes

Use:

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

Result:

Hi,

Curtis!

18
votes

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

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

This worked for me

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

(react-native 0.41.0)

14
votes

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

7
votes

Better yet: if you use styled-components , you can do something like this:

import React, { Component } from 'react';
import styled from 'styled-components';

const Text = styled.Text`
  text-align: left;
  font-size: 20px;
`;

export default class extends Component {

 (...)

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

}
6
votes

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

5
votes

There are two options:

Option 1: Using Template Literals.

const Message = 'This is a message';

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

Result:

Hi~
This is a message

Option 2: Use {'\n'} as line breaks.

<Text>

   Hello {'\n'}

   World!

</Text>

Result:

Hello
World!
4
votes

You can try using like this

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

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>
2
votes

You can use `` like this:

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

You can do it as follows:

{'Create\nYour Account'}

2
votes

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>
     )  
  }
2
votes

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

<Text>

   Hello {'\n'}

   World!

</Text>
2
votes

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
2
votes

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.

2
votes

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

2
votes

do this:

<Text>

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

<Text/>
2
votes

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

2
votes

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

1
votes

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

0
votes

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

0
votes

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;
0
votes

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
0
votes

sometimes I write like this:

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

(as it looks more clear for myself)

0
votes

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

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

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>
    )
}}
-1
votes

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.