How can I insert a line break into a text component in React Native?

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.

I cannot test it right now but this should do it:

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

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.

This worked for me

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

(react-native 0.41.0)

Use:

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

Result:

Hi,

Curtis!

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

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

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

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:

You can try using like this

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

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

Adding a closing tag to the line break jsx seemed to work for me.

<text>First Line<br></br>Second Line</text>

Output:

First Line Second Line

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue