Explain Codes LogoExplain Codes Logo

How can I insert a line break into a <Text> component in React Native?

javascript
react-native
template-literals
text-component
Anton ShumikhinbyAnton Shumikhin·Aug 29, 2024
TLDR

To add a line break in a <Text> component in React Native, leverage the newline character \n:

<Text>{"Hello first line\nHello second line"}</Text>

In a dynamic array of strings, create line breaks by joining the elements with \n:

<Text>{ ["Hello first line", "Hello second line"].join('\n') }</Text>

Better handling of line breaks

React Native <Text> components interpret text differently than HTML. In HTML, <br> is used for line breaks; however, in React Native, '\n' is used for line break. Make sure to enclose \n within curly braces: {}.

Going multiline with template literals

You can create multiline strings with ES6 template literals which preserve line breaks:

<Text>{`First line, reporting! Second line, right here!`}</Text>

// Who knew lines could report? Coding brings life to anything, eh?

Leverage text styling options

Although whiteSpace property from CSS does not exist in React Native, flexWrap: 'wrap' and maxWidth can be helpful. Here, text auto-wraps to a new line when the defined limit is reached.

While presenting preformatted code, use a custom text component to retain formatting:

<Text style={{ fontFamily: 'monospace' }}> {`Code block: You can't spell "Believe" without "lie"! `} </Text>

// Fun fact: Code blocks double as a thought of the day platform!

Remember to always consider the React Native version you're working with, as certain features may vary.

Catering to Exceptions and Adapting Styles

Converting web API data embedded with <br/> tags to line breaks can be handled this way:

const textWithLineBreaks = yourTextFromApi.replace(/<br\/?>/g, '\n'); <Text>{textWithLineBreaks}</Text>

// Out with the old <br/>, in with the new \n!

The maxWidth style can handle text wrapping, reducing the need for manual line breaks:

<Text style={{ maxWidth: 200 }}> {"I'm shooting for the stars, but I got caught up in the maxWidth!"} </Text>

Pitfall prevention

Stay cautious of unwanted spaces in your JSX while inserting line breaks. Also, ensure backticks surrounding the string in template literals have no leading or trailing spaces.