I want to insert a new line (like \\r\\n,
) in a Text component in React Native.
If I have:
Hi~
this
You can do it as follows:
{'Create\nYour Account'}
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 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.
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
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>
)
}}
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>
);
}
}