Curtis
Curtis

Reputation: 6642

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.

Upvotes: 663

Views: 1111514

Answers (30)

{"/n"} <--- for new line

{" "} <--- for space

for example

<Text>Hello my name is{" "} John</Text> <--- for spacing

<Text>Hello my name is {"/n"} John</Text> <--- for new line

Upvotes: -1

Vibhanshu Sharma
Vibhanshu Sharma

Reputation: 16

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

Upvotes: 0

Mahdi Eslami
Mahdi Eslami

Reputation: 99

do this:

  <Text>
    This is the first line.{"\n"}This is the second line.
  </Text>

Upvotes: 4

goRGon
goRGon

Reputation: 4451

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.`}

Upvotes: 0

pwellner
pwellner

Reputation: 30

An empty View does the trick

<Text> some text </Text>
<View />
<Text> another line </Text>

Upvotes: -3

M.Hassam Yahya
M.Hassam Yahya

Reputation: 442

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

Upvotes: 12

belards
belards

Reputation: 81

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

Upvotes: 3

Muhammad Numan
Muhammad Numan

Reputation: 25403

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>

Upvotes: 75

Bharathi Devarasu
Bharathi Devarasu

Reputation: 8327

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/

Upvotes: 3

Muhammad Humza
Muhammad Humza

Reputation: 187

This should do the trick !

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

Upvotes: -2

Charlie Morton
Charlie Morton

Reputation: 787

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>

Upvotes: 3

lodey
lodey

Reputation: 304

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

Upvotes: 0

Telmo Dias
Telmo Dias

Reputation: 4178

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

Upvotes: 12

Rishi Bhachu
Rishi Bhachu

Reputation: 172

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

Upvotes: -2

mrxrinc
mrxrinc

Reputation: 113

sometimes I write like this:

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

(as it looks more clear for myself)

Upvotes: 0

pankaj
pankaj

Reputation: 1914

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

Upvotes: -2

Farbod Aprin
Farbod Aprin

Reputation: 1186

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>

Upvotes: -3

asukiaaa
asukiaaa

Reputation: 1674

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

Upvotes: 1

abduljeleelng
abduljeleelng

Reputation: 55

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

Upvotes: 2

Shahmeer Khan
Shahmeer Khan

Reputation: 160

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

Upvotes: 6

errkk
errkk

Reputation: 305

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.

Upvotes: -1

user13018007
user13018007

Reputation:

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>

Upvotes: 3

user3086644
user3086644

Reputation: 59

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

Upvotes: -2

Iresha Amarasinghe
Iresha Amarasinghe

Reputation: 87

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

Upvotes: -2

Vadorequest
Vadorequest

Reputation: 18019

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

Upvotes: 4

ilike2breakthngs
ilike2breakthngs

Reputation: 425

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.

Upvotes: 14

Akhil Balakrishnan
Akhil Balakrishnan

Reputation: 616

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

Upvotes: 3

Max Oriola
Max Oriola

Reputation: 1374

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;

Upvotes: 1

Curious96
Curious96

Reputation: 401

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

<Text>

   Hello {'\n'}

   World!

</Text>

Upvotes: 3

Chris Ghenea
Chris Ghenea

Reputation: 12973

This should do it:

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

Upvotes: 1107

Related Questions