I want to insert a new line (like \\r\\n,
) in a Text component in React Native.
If I have:
Hi~
this
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.
This worked for me
<Text>{`Hi~\nthis is a test message.`}</Text>
(react-native 0.41.0)
If at all you are displaying data from state variables, use this.
<Text>{this.state.user.bio.replace('<br/>', '\n')}</Text>
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;
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>
)
}
You can use {'\n'}
as line breaks.
Hi~ {'\n'} this is a test message.