Reputation: 6642
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
Reputation: 39
{"/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
Reputation: 99
do this:
<Text>
This is the first line.{"\n"}This is the second line.
</Text>
Upvotes: 4
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
Reputation: 30
An empty View does the trick
<Text> some text </Text>
<View />
<Text> another line </Text>
Upvotes: -3
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
Reputation: 25403
<Text>
line 1{"\n"}
line 2
</Text>
<Text>{`
line 1
line 2
`}</Text>
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>
use maxWidth
for auto line break
<Text style={{ maxWidth:200}}>this is a test message. this is a test message</Text>
Upvotes: 75
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
Reputation: 187
This should do the trick !
<Text style={{styles.text}}>{`Hi~\nthis is a test message.`}</Text>
Upvotes: -2
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
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
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
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
Reputation: 113
sometimes I write like this:
<Text>
You have {" "}
{remaining}$ {" "}
from{" "}
{total}$
<Text>
(as it looks more clear for myself)
Upvotes: 0
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
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
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
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
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
Reputation: 305
React won't like you putting HTML <br />
in where it's expecting text, and \n
s 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
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
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
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>
Upvotes: 4
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
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
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
Reputation: 401
Just put {'\n'}
within the Text tag
<Text>
Hello {'\n'}
World!
</Text>
Upvotes: 3
Reputation: 12973
This should do it:
<Text>
Hi~{"\n"}
this is a test message.
</Text>
Upvotes: 1107