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




react<br> (10)

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>
  );
 }

}

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.

I cannot test it right now but this should do it:

<Text>
Hi~{"\n"}
this is a test message.
</Text>

If at all you are displaying data from state variables, use this.

<Text>{this.state.user.bio.replace('<br/>', '\n')}</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


Use \n in text and css white-space: pre-wrap;


Use:

<Text>{`Hi,\nCurtis!`}</Text>

Result:

Hi,

Curtis!


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 do it as follows:

{'Create\nYour Account'}


You can use {'\n'} as line breaks. Hi~ {'\n'} this is a test message.


You can use `` like this:

<Text>{`Hi~
this is a test message.`}</Text>






newline