I want to insert a new line (like \\r\\n,
) in a Text component in React Native.
If I have:
Hi~
this
This should do it:
<Text>
Hi~{"\n"}
this is a test message.
</Text>
You can use `` like this:
<Text>{`Hi~
this is a test message.`}</Text>
In case anyone is looking for a solution where you want to have a new line for each string in an array you could do something like this:
import * as React from 'react';
import { Text, View} from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
description: ['Line 1', 'Line 2', 'Line 3'],
};
}
render() {
// Separate each string with a new line
let description = this.state.description.join('\n\n');
let descriptionElement = (
<Text>{description}</Text>
);
return (
<View style={{marginTop: 50}}>
{descriptionElement}
</View>
);
}
}
See snack for a live example: https://snack.expo.io/@cmacdonnacha/react-native-new-break-line-example
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:
There are two options:
Option 1: Using Template Literals.
const Message = 'This is a message';
<Text>
{`
Hi~
${Message}
`}
</Text>
Result:
Hi~
This is a message
Option 2: Use {'\n'} as line breaks.
<Text>
Hello {'\n'}
World!
</Text>
Result:
Hello
World!
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>