Word break react native

Is there a way to control the word-break behaviour for text within a Text component? With a multiple-line Text component on iOS it automatically breaks the text where there are word breaks (I haven’t checked android yet, but I’d need it to work there too). I was hoping to change that behaviour to break on the per-character level, like you can do this CSS rule:

word-break: break-all;

asked Aug 20, 2019 at 17:11

benjamin.keen's user avatar

transform <text>str</text> to <View><text>s</text><text>t</text><text>r</text></View> by using split & map!

export default class PageCard extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tail: false,
            longWord: 'longWord longWord bbbbbbbbbbbbbbbbbbbbb longWord longWord longWord',
            longWordTail: ' longWord longWord longWord bbbbbbbbbbbbbbbbbbbbb longWord longWord longWord',
            longWordTail2: ' longWord longWord bbbbbbbbbbbbbbbbbbbbb longWord longWord longWord',
        };
    }

    render() {
        return (
            <ScrollView style={{flex: 1, paddingTop: 60, paddingHorizontal: 10}}>
                
                <View style={Styles.breakWordWrap}>
                    <Text numberOfLines={2} ellipsizeMode="tail" style={Styles.breakWord}>
                        {this.state.longWord}
                    </Text>
                </View>

                <View style={Styles.breakWordWrap}>
                    {
                        this.breakWord(this.state.longWord)
                    }
                </View>

                <View style={[Styles.breakWordWrap, Styles.breakWordWrapTail]}>
                    {
                        this.breakWord(this.state.longWordTail)
                    }
                </View>

                <View style={[Styles.breakWordWrap, Styles.breakWordWrapTail]}>
                    {
                        this.breakWord(this.state.longWordTail, true)
                    }
                </View>

                {/*<View style={[Styles.breakWordWrap, Styles.breakWordWrapTail]}>*/}
                {/*    {*/}
                {/*        this.breakWord(this.state.longWordTail2, true)*/}
                {/*    }*/}
                {/*</View>*/}

            </ScrollView>
        )
    }

    breakWord = (str = '', tail = false) => {
        let strArr = (tail ? str + ' ' : str).split('');
        return strArr.map((item, index) => tail && strArr.length === index + 1 ?
            <Text key={item + index} style={[Styles.breakWord, Styles.breakWordTail, !this.state.tail && Styles.breakWordTailHide]}>...</Text> :
            (tail && strArr.length === index + 2 ? <Text key={item + index} style={[Styles.breakWord]} onLayout={this.breakWordLast}>{item}</Text>
                : <Text key={item + index} style={[Styles.breakWord]}>{item}</Text>)
        );

    }

    breakWordLast = (e) => {
        console.log(e.nativeEvent.layout)
        if (e.nativeEvent.layout.y > 50) {
            this.setState({
                tail: true
            })
        }
    }

}
const Styles = {
    box: {
        marginTop: 10,
    },
    title: {
        fontWeight: 'bold',
        color: '#333',
        textAlign: 'center'
    },
    breakWordWrap: {
        flexWrap: 'wrap',
        flexDirection: 'row',
        // not
        borderWidth: 1,
        marginTop: 30,
    },
    breakWordWrapTail: {
        position: 'relative',
        height: 50,
        overflow: 'hidden'
    },
    breakWord: {
        lineHeight: 25
    },
    breakWordTail: {
        position: 'absolute',
        backgroundColor: '#fff',
        right: 0,
        bottom: 0,
        height: 25
    },
    breakWordTailHide: {
        opacity: 0
    }
}

answered Jul 16, 2020 at 15:47

daidaibenben's user avatar

There is an Android-only textbreakstrategy property for Text components that allows some control on how a text should be split. The property values map to Android’s native android:breakStrategy values.

This property does not seem to translate to iOS though.

Otherwise, if you have preknowledge about the Text value, you could indicate text split with a Soft Hyphen

<Text>aaaaaaaaaaaaaaaaaa bbbbbbbbbbb&shy;CCCCC.</Text>

This would render as:

aaaaaaaaaaaaaaaaaa bbbbbbbbbbb-
CCCCC.

If neither suffice, I suppose this is beyond the capabilities of a Text component and you may have to revert to another component. Maybe one that renders simple html.

answered Aug 20, 2019 at 21:29

tvanlaerhoven's user avatar

1

There is the possibility with following code

<Text style={{ flexShrink: 1 }}>

answered Oct 19, 2022 at 7:51

Krish Chary's user avatar

0

Try add flexWrap: "wrap" to the style of the Text component

Example:

Code

<View style={styles.container}>
  <Text style={styles.text}>{text}</Text>
</View>

Style

export default StyleSheet.create({
  container: {
      flexDirection: 'row',
      alignItems: 'center',
  },
  text: {
    width: 0,
    flexGrow: 1,
    flex: 1,
  }
});

answered Aug 20, 2019 at 17:23

Trần Công's user avatar

Trần CôngTrần Công

2801 silver badge5 bronze badges

3

description

React Native for web provides access to browser-only style properties. The following styles apply to any primitive that extends `TextViewStylePropTypes` like `<TextInput />`.

Text

The API

textIndent

Sets the length of empty space (indentation) that is put before lines of text in a block.

Type: number | string

Conversion

// CSS
- text-indent: 30px;

// React Native
+ textIndent: 30,

textOverflow

Sets how hidden overflow content is signaled to users. It can be clipped, display an ellipsis (‘‘), or display a custom string.

Type: string | 'each-line' | 'hanging' | Array<T>

Conversion

// CSS
- text-overflow: 5px hanging each-line;

// React Native
+ textOverflow: [5, "hanging", "each-line"],

textRendering

Provides information to the rendering engine about what to optimize for when rendering text. The browser makes trade-offs among speed, legibility, and geometric precision.

Type: 'auto' | 'geometricPrecision' | 'optimizeLegibility' | 'optimizeSpeed'

Conversion

// CSS
- text-rendering: optimizeLegibility;

// React Native
+ textRendering: "optimizeLegibility",

unicodeBidi

The unicodeBidi property, together with the direction property, determines how bidirectional text in a document is handled. For example, if a block of content contains both left-to-right and right-to-left text, the user-agent uses a complex Unicode algorithm to decide how to display the text. The unicodeBidi property overrides this algorithm and allows the developer to control the text embedding.

Type: 'normal','bidi-override','embed','isolate','isolate-override','plaintext'

Conversion

// CSS
- unicode-bidi: embed;

// React Native
+ unicodeBidi: "embed",

whiteSpace

Sets how white space inside an element is handled. Note: To make words break within themselves, use overflow-wrap, word-break, or hyphens instead.

Type: string

Conversion

// CSS
- white-space: word-break;

// React Native
+ whiteSpace: "word-break",

wordBreak

Sets whether line breaks appear wherever the text would otherwise overflow its content box.

Type: 'normal', 'break-all', 'break-word', 'keep-all'

Conversion

// CSS
- word-break: break-all;

// React Native
+ wordBreak: "break-all",

wordWrap

Applies to inline elements, setting whether the browser should insert line breaks within an otherwise unbreakable string to prevent text from overflowing its line box.

In CSS word-wrap is also known as overflow-wrap

Type: 'normal' | 'anywhere' | 'break-word'

Conversion

// CSS
- word-wrap: anywhere;

// React Native
+ wordWrap: "anywhere",

WebkitFontSmoothing

MozOsxFontSmoothing

Controls the application of anti-aliasing when fonts are rendered.

Type: string

Conversion

// CSS
- font-smooth: always;

// React Native
+ WebkitFontSmoothing: "always",
+ MozOsxFontSmoothing: "always",

Aug 03, 2022 . Admin

In this tutorial, you will learn react native text component wrap. We will look at example of react native text wrap to next line. you can see how to wrap text in react native. In this article, we will implement a how to wrap text in react native. Let’s get started with react native text wrap break word.

Sometimes, we need to wrap text in react native on screen. here we will add To wrap React Native text on the screen, we can set flexWrap to ‘wrap’. so let’s see simple example

Step 1: Download Project

In the first step run the following command to create a project.

expo init ExampleApp

Step 2: App.js

In this step, You will open the App.js file and put the code.

import React from "react";
import { StyleSheet, Text, View} from 'react-native';

export default function App() {
  return (
    <View style={{ flexDirection: 'row',alignItems: 'center' ,justifyContent: 'center',flex:1}}>
      <Text style={{ flex: 1, flexWrap: 'wrap' }}>
        <View>
          <Text>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</Text>
        </View>
        <View>
          <Text>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</Text>
        </View>
      </Text>
    </View>
  );
}

Step 3: Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output:

It will help you…

#React Native

✌️ Like this article? Follow me on Twitter and Facebook. You can also subscribe to RSS Feed.

  • React Native Image Slider Box Example
  • React Native Action Button Example
  • React Native Convert Any Input Value in Md5 Example
  • React Native CountDown Timer Example
  • How to Get IP Address in React Native?
  • How to Filter Array of Objects in React Native App?

Getting the text to wrap because flexWrap ain’t cuttin’ it

I don’t know about you, but React Native’s Layout and Flexbox model is confusing  sometimes. That’s because it doesn’t always behave like it does in CSS. Really all you want is React Native text overflow to just wrap and call it a day. But it’s not so straightforward like that.

Lets wrap your head around flexWrap

In React Native, you may be tempted to try the flexWrap because it’s the only option with the word “wrap” in it. There’s even some people recommending using that style, but that style’s main concern is something else: it’s to break flexbox children, not text.

After some research, I found this GitHub issue. 

Now, the solutions that were successful used the flexWrap option, but upon testing the flexWrap option was redundant. Some of the solutions used “flex: 1” on the parent view. I personally didn’t want to do that since that would negatively affect the layout of my app. I wanted my particular parent view to grow to the available space that was left. 

If you understand “flex: 1” you’ll know that it’ll distribute the dimension in relationship to its siblings. 

Lets say you do the following:

How flex works. It’s not related to your muscles.

If you understand “flex: 1” you’ll know that it’ll distribute the dimension in relationship to its siblings. 

Lets say you do the following:

				
					import * as React from "react";
import {View} from "react-native";


    
        One
    
    
        Two
    
    
        Three
    


				
			

Notice how there’s three children with “flex: 1”. In this case, the default flexbox direction is column (or vertical), so each children’s height will be distributed equally 1 + 2 + 1 = 4. So the first and last child takes 1/4th of the height, while the middle child gets 2/4ths of the height (or 1/2).

Going back to the text wrap issue in React Native. What I wanted to do was only have the text breaking and not affecting the overall flexbox layout. So in order to do that you’ll need to apply the “flex: 1” to the Text component itself, and for the parent you’ll add “flexDirection: row“.

Here’s how that looks like:

				
					import * as React from 'react';
import { Text, View, SafeAreaView } from 'react-native';

export default function App() {
  return (
    
        
            One
        
        
            Two very long text
        
        
            Three
        
    
  );
}

				
			

If you run the previous code you’ll see that it works just fine on native devices, but the text doesn’t wrap for web. So to fix that just add “width: 1” to the Text component like so.

				
					
        Two very long text
    
				
			

The secret overflow sauce

It’s this specific combination of parent and child styles that break texts for both native devices and web. If you don’t want to add the “width: 1” across all platforms, you could just use “Platform.OS” and conditionally check for “web”.

So now lets see how that looks with the fix:

				
					import * as React from 'react';
import { Text, View, SafeAreaView } from 'react-native';

export default function App() {
  return (
    
        
            One
        
        
            Two very long text
        
        
            Three
        
    
  );
}

				
			

I’ve tried that in Brave (essentially Chrome), Safari, Firefox, and Microsoft Edge. They all accept the fix. It doesn’t seem like it’s something officially documented as I’ve tried to look up the W3 docs and there’s nothing that would allude to doing this. So consider this a “hack” just like back in the old days when we had to support IE 6+ (🤢). 

The only thing that I could assume here is that the flex width of the parent is growing to the full size of its child because of “flexGrow: 1” and then adding “width: 1” makes the flex child shrink less than the threshold causing “flexGrow: 1” to use the remainder of the width available from the parent container’s 160 total width. Basically 160 – 50 – 50 (container width minus the 2 views with 50) left us with 60 and that’s what flexGrow used instead of the intrinsic width of the text context which was longer than 60 units (px in web).

I hope this was useful to you and you’re able to create cross-platform React Native apps.



  • Expo, React Native, React Native word break, wrap content

Есть ли способ указать режим разрыва строки в реакции, родной с компонентом Text?

По умолчанию Text Component обертывает текст словами (т.е. Если он не может соответствовать слову, он переносит его на следующую строку). Я хочу обернуть текст символами (т.е. он должен отображать как можно больше символов из слова и перейти к следующей строке)

Например: мы можем указать реализовать это в iOS, установив lineBreakMode в UILineBreakModeCharacterWrap на UILabel. Я пытаюсь добиться чего-то подобного.

02 июль 2018, в 14:32

Поделиться

Источник

2 ответа

Используйте flexWrap, как hardik bar сказал:

flexWrap контролирует, могут ли дети обертываться после того, как они попали в конец контейнера для гибких контейнеров

Вот пример ссылки expo

Aung Myat Hein
02 июль 2018, в 14:47

Поделиться

Попробуйте этот код

<View style={{flexDirection:'row', flex: 1, flexWrap: 'wrap',flexShrink: 1}}>
   <Text> You miss fdddddd dddddddd You    missfddddddddddddddasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasds</Text> </View>

hardik bar
02 июль 2018, в 12:50

Поделиться

Ещё вопросы

  • 0Как получить начальный тег и конечный тег элемента HTML с помощью PHP
  • 0jquery attr (‘selected’, ‘selected’) для опции, не работающей в IE
  • 1почему мы не можем установить значение по умолчанию переменной типа char в »
  • 1Как я могу изменить RequestedTheme элемента из элемента управления во всплывающем окне настроек?
  • 1Случай переключения Javascript, который запускает код, когда любой случай верен?
  • 1Перекрывающиеся виджеты QGridLayout
  • 0Можно ли приравнять имя функции к другому имени функции?
  • 1Ошибка: не удалось найти файл привязок. Пробовал: (Webpack)
  • 1Удалить существующую базу данных и воссоздать схему в Hibernate
  • 0MySQL, имеющий количество (*)> 1
  • 0как получить значение метки в jquerymobile и разобрать его в int
  • 1Как мне найти более описательный путь XML для моего веб-сайта Selenium?
  • 0Каково значение флажка в виде целого числа?
  • 0Ошибка Angularjs CORS на некоторых машинных браузерах Mac
  • 1Повторение изображения по вертикали и горизонтали в Java
  • 0Выбор CMS с открытым исходным кодом: REST in REST out
  • 0Возвращение указателей из функций
  • 0Разделение сборки и теста на Дженкинса
  • 1Получить токен доступа в Instagram с помощью python
  • 0Сложное Условное
  • 0Сервисный синглтон на всех контроллерах
  • 0Оператор + не возвращает то, что я ожидаю C ++
  • 1Заполнение сложных объектов из листа Excel и передача его в качестве параметра в [Теорию]
  • 0Выберите строку с наибольшим значением между двумя таблицами, а также выберите другие столбцы в группе по
  • 1Как отобразить таблицу, содержащую данные внутри окна сообщения, используя C #
  • 0Как добавить «или» в pathsubst в Makefile
  • 0Проблемы с CSS, которые не могут найти класс
  • 0не может отследить серую клетку в лабиринте
  • 1Улучшение производительности на картах Google, рисующих длинные пути
  • 0Как я могу передать данные из службы в мой контроллер?
  • 1Как извлечь строку в пандах с помощью регулярных выражений?
  • 1Как использовать операторы If из JTextFields [duplicate]
  • 0анимация div с помощью jquery
  • 1java.net.socketException: истечение времени работы при запуске приложения на реальном устройстве
  • 1Как обновить JPanel во время выполнения?
  • 1Pandas read_csv не вызывает исключение для плохих строк, когда указаны имена
  • 1Доступ к представлениям в Android ActionBar
  • 1Я хочу завершить все приложение, когда пользователь нажимает кнопку назад в Android
  • 1Как получить определенные значения записи из базы данных SQL, хранящейся на сервере, и обновить эти значения в базе данных SQLite для Android?
  • 1Посоветуйте правильный способ массового добавления значений в ячейку, зависит от другой ячейки
  • 1Повторяющиеся записи в ответе сервера .net
  • 1полноэкранный браузер изображений вызывается из GridView
  • 0Передать массив из PHP в JS
  • 0Использование HTML в объекте JSON
  • 0Синтаксическая ошибка в операторе SQL «INSERT INTO
  • 0Хотите добавить проверку в мой код, если таблица не существует, она должна создать новую таблицу в Java [duplicate]
  • 0Основная форма с использованием HTML и Php
  • 1Android: перезапуск с новой версией разрабатываемого приложения
  • 1Могу ли я гарантировать, что мое Java-приложение будет выполняться с помощью Security Manager с ограничительной политикой?
  • 1Как сравнить длину слов во входном тексте и отсортировать их по значению длины

Сообщество Overcoder

In this Example of MultiLine Text / Break Text in React Native, we will see how can you break the text of a Text Component in multiline using a new line character. So let’s get started.

To Break the Text

<View style={styles.container}>
  <Text style={styles.paragraph}>
  Hello This is an example of 
    {'n'}
    multiline text
  </Text>
  <Text style={styles.paragraph}>
     {`Here is an other way to set multiline text.`}
  </Text>
</View>

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the —version argument:

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

This will make a project structure with an index file named App.js in your project directory.

Code for MultiLine Text

Open App.js in any code editor and replace the code with the following code.

App.js

//MultiLine Text / Break Text in React Native
//https://aboutreact.com/multi-line-text-break-text-in-react-native/

//import React in our code
import React from 'react';

//import all the components we are going to use
import {SafeAreaView, StyleSheet, View, Text} from 'react-native';

const App = () => {
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={styles.container}>
        <Text style={styles.paragraph}>
          Hello This is an example of
          {'n'}
          multiline text
        </Text>
        <Text style={styles.paragraph}>
          {`Here is an other way to 
          set multiline text.`}
        </Text>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: 30,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    textAlign: 'center',
  },
});

export default App;

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

1. Start Metro Bundler

First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command

npx react-native start

Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.

2. Start React Native Application

To run the project on an Android Virtual Device or on real debugging device

npx react-native run-android

or on the iOS Simulator by running (macOS only)

npx react-native run-ios

Output Screenshots

Output in Online Emulator

This is how you can Underline Text in React Native. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

Я хочу вставить новую строку (например, r n, ‹br /›) в текстовый компонент в React Native.

Если у меня есть:

<text>
<br />
Hi~<br />
this is a test message.<br />
</text>

Затем React Native отображает Hi~ this is a test message.

Можно ли отобразить текст, чтобы добавить новую строку следующим образом:

Hi~
this is a test message.

person
Curtis
  
schedule
09.09.2015
  
source
источник


Ответы (33)

Это должно сделать это:

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

person
Chris Ghenea
  
schedule
09.09.2015

Вы также можете:

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

На мой взгляд, это проще, потому что вам не нужно вставлять что-то в строку; просто оберните его один раз, и он сохранит все ваши разрывы строк.

person
Venryx
  
schedule
21.11.2016

Использовать:

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

Результат:

Hi,

Кертис!

person
COdek
  
schedule
17.05.2018

Если вы вообще отображаете данные из переменных состояния, используйте это.

<Text>{this.state.user.bio.replace('<br/>', 'n')}</Text>

person
Edison D’souza
  
schedule
30.06.2017

Это сработало для меня

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

(реагировать-родной 0.41.0)

person
Olivier
  
schedule
13.02.2017

Вы можете использовать {'n'} как разрывы строк. Привет ~ {‘ n’}, это тестовое сообщение.

person
Vijay Suryawanshi
  
schedule
17.11.2017

Еще лучше: если вы используете styled-components, вы можете сделать что-то вроде этого:

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

}

person
Telmo Dias
  
schedule
28.11.2018

Мне нужно было однострочное решение с разветвлением в тернарном операторе, чтобы мой код оставался с хорошим отступом.

{foo ? `First line of textnSecond line of text` : `Single line of text`}

Превосходная подсветка синтаксиса помогает выделить символ разрыва строки:

Превосходная подсветка синтаксиса

person
Beau Smith
  
schedule
31.03.2017

Есть два варианта:

Вариант 1. Использование шаблонных литералов.

const Message = 'This is a message';

<Text>
{`
  Hi~
  ${Message}
`}
</Text>

Результат:

Hi~
This is a message

Вариант 2: Используйте {‘ n’} в качестве разрыва строки.

<Text>

   Hello {'n'}

   World!

</Text>

Результат:

Hello
World!

person
Biplov Kumar
  
schedule
10.10.2020

Вы можете попробовать вот так

<text>{`${val}n`}</text>

person
Pankaj Agarwal
  
schedule
29.08.2018

Простые обратные кавычки (функция ES 6)

РЕШЕНИЕ 1

const Message = 'This is a message';

<Text>
{`
  Hi~
  ${Message}
`}
</Text>

РЕШЕНИЕ 2 Добавьте n в текст

<Text>
Hi~{"n"}
This is a message.
</Text>

person
Community
  
schedule
11.10.2020

Вы можете использовать « вот так:

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

person
Idan
  
schedule
06.12.2018

Сделать это можно следующим образом:

{‘Create nYour Account’}

person
Himanshu Ahuja
  
schedule
14.03.2019

Вы также можете просто добавить его как константу в свой метод рендеринга, чтобы его было легко использовать повторно:

  render() {
    const br = `n`;
     return (
        <Text>Capital Street{br}Cambridge{br}CB11 5XE{br}United Kingdom</Text>
     )  
  }

person
Tim J
  
schedule
27.06.2019

Просто поместите {'n'} в текстовый тег

<Text>

   Hello {'n'}

   World!

</Text>

person
Curious96
  
schedule
16.11.2019

https://stackoverflow.com/a/44845810/10480776 Ответ @Edison D’souza был именно тем, что я искал . Однако он заменял только первое вхождение строки. Вот мое решение для обработки нескольких тегов <br/>:

<Typography style={{ whiteSpace: "pre-line" }}>
    {shortDescription.split("<br/>").join("n")}
</Typography>

Извините, я не смог прокомментировать его сообщение из-за ограничения оценки репутации.

person
ilike2breakthngs
  
schedule
03.05.2020

Вот решение для React (не React Native) с использованием TypeScript.

Та же концепция может быть применена к 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;

Использование:

<Text>
  {`
    This page uses server side rendering (SSR)

    Each page refresh (either SSR or CSR) queries the GraphQL API and displays products below:
  `}
</Text>

Отображает:  введите здесь описание изображения

person
Vadorequest
  
schedule
06.05.2020

сделай это:

<Text>

 { "Hi~ n this is a test message." }

<Text/>

person
Mahdi Eslami
  
schedule
29.12.2020

это хороший вопрос, вы можете сделать это несколькими способами: Первый

<View>
    <Text>
        Hi this is first line  {n}  hi this is second line 
    </Text>
</View>

что означает, что вы можете использовать { n} обратную косую черту n для разрыва строки

Второй

<View>
     <Text>
         Hi this is first line
     </Text>
     <View>
         <Text>
             hi this is second line 
         </Text>
     </View>
</View>

это означает, что вы можете использовать другой компонент ‹View› внутри первого ‹View› и обернуть его вокруг ‹Text› компонента

Счастливое кодирование

person
Shahmir Khan
  
schedule
29.12.2020


Если вы получаете данные из state variable or props, компонент Text имеет свойство стиля с minWidth, maxWidth.

пример

const {height,width} = Dimensions.get('screen');

const string = `This is the description coming from the state variable, It may long thank this` 

<Text style={{ maxWidth:width/2}}>{string}</Text>

Это отобразит текст на 50% ширины вашего экрана.

person
abduljeleelng
  
schedule
03.02.2021

Просто используйте {» n»} там, где хотите разорвать линию

person
M.Hassam Yahya
  
schedule
06.09.2019

Если кто-то ищет решение, в котором вы хотите иметь новую строку для каждой строки в массиве, вы можете сделать что-то вроде этого:

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('nn');

    let descriptionElement = (
      <Text>{description}</Text>
    );

    return (
      <View style={{marginTop: 50}}>
        {descriptionElement}
      </View>
    );
  }
}

См. Живой пример закуски: https://snack.expo.io/@cmacdonnacha/react-native-new-break-line-example

person
ReturnOfTheMac
  
schedule
15.05.2019

Другой способ вставить <br> между текстовыми строками, которые определены в массиве:

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;
  }, []);

Тогда текст можно использовать как переменную:

<Text>{textContent}</Text>

Если недоступно, Fragment можно определить следующим образом:

const Fragment = (props) => props.children;

person
Max Oriola
  
schedule
26.02.2020

Этот код работает в моей среде. (реагировать-родной 0.63.4)

const charChangeLine = `
`
// const charChangeLine = "n" // or it is ok

const textWithChangeLine = "abcndef"

<Text>{textWithChangeLine.replace('¥n', charChangeLine)}</Text>

Результат

abc
def

person
asukiaaa
  
schedule
08.02.2021

иногда я пишу так:

<Text>
  You have {" "}
  {remaining}$ {" "}
  from{" "}
  {total}$
<Text>

(как мне кажется более понятным)

person
mrxrinc
  
schedule
09.04.2021

2021 год, это работает для значения состояния REACT (вы должны добавить пустые блоки div, как и оператор возврата)

this.setState({form: (<> line 1 <br /> line 2 </>) })

person
Rishi Bhachu
  
schedule
11.06.2021

Зачем так много работать? это 2020 год, создайте компонент для решения таких проблем

    export class AppTextMultiLine extends React.PureComponent {
    render() {
    const textArray = this.props.value.split('n');
return (
        <View>
            {textArray.map((value) => {
               return <AppText>{value}</AppText>;
            })}
        </View>
    )
}}

person
user3086644
  
schedule
21.09.2020

React не понравится, если вы поместите HTML <br /> туда, где он ожидает текст, а ns не всегда отображаются, кроме как в теге <pre>.

Возможно, заключите каждую строку (абзац) с разрывом строки в тег <p> следующим образом:

{text.split("n").map((line, idx) => <p key={idx}>{line}</p>)}

Не забывайте key, если вы повторяете компоненты React.

person
errkk
  
schedule
07.12.2020

Я использовал p Tag для новой строки. поэтому здесь я вставил код, который поможет любому.

const new2DArr =  associativeArr.map((crntVal )=>{
          return <p > Id :  {crntVal.id} City Name : {crntVal.cityName} </p>;
     });

person
pankaj kumar
  
schedule
16.03.2021

Используйте n в тексте и css white-space: pre-wrap;

person
Alexey Zavrin
  
schedule
24.07.2018

Эй, просто поставь их вот так, у меня работает!

   <div>
       <p style={{ fontWeight: "bold", whitespace: "pre-wrap" }}>
         {" "}
         Hello {"n"}
       </p>
         {"n"}
       <p>I am here</p>
   </div>

person
Farbod Aprin
  
schedule
02.03.2021

This tutorial explains how to add multi-line text/break text in react native application. This is very simple and easy as well. you need use {‘n’} as line breaks in text component, whenever you need to add line break in react native application.

Multi-Line Text / Break Text in React Native

Lets see the below example, where we are using line break statement in Text component in react native application. This will display the text in new line and in organised manner.

import React, { Component } from 'react';
import { StyleSheet, Text, View,} from 'react-native';


export default class App extends Component {

  render() {
    return (
      <View style={styles.Container}>

        <Text style={styles.paragraph}>
          Hello This is an example of
          {'n'}
          multiline text
        </Text>

        <Text style={styles.paragraph}>{`Here is an other way to 
        set multiline text.`}</Text>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  Container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Screenshot : 

Multi-Line Text / Break Text in React Native

This is all about Multi-Line Text / Break Text in React Native. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

Hello friends, Today again we came back with a simple but useful tutorial of react native. As we all know at the time of writing Essay and Application we have to break line and move our content to next row. Now on a Text page it is very simple all we have to do move our hand to next row. But what if we want to break line from middle in text and move into next row in react native. Here comes {‘n’} the backslash + small n into magic. Using the n we can insert line break on text component in react native.

Contents in this project Example of Insert Line Break on Text Component in React Native :-

1. Open your project’s main App.js file and import StyleSheet, SafeAreaView and Text component.

import React from ‘react’;

import { StyleSheet, SafeAreaView, Text } from ‘react-native’;

2. Creating our main App component.

export default function App() {

}

3. Creating return() block, Here we would make 2 sample Text component with Break line text.

  return (

    <SafeAreaView style={styles.MainContainer}>

      <Text style={styles.text}>

        Hello, {‘n’} How are you ?

      </Text>

      <Text style={styles.text}>

        Hi, {‘n’} Welcome Here.

      </Text>

    </SafeAreaView>

  );

4. Creating Style.

const styles = StyleSheet.create({

  MainContainer: {

    flex: 1,

  },

  text: {

    fontSize: 25,

    color: ‘black’,

    textAlign: ‘center’,

  }

});

5. Complete Source Code for App.js File :-

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

import React from ‘react’;

import { StyleSheet, SafeAreaView, Text } from ‘react-native’;

export default function App() {

  return (

    <SafeAreaView style={styles.MainContainer}>

      <Text style={styles.text}>

        Hello, {‘n’} How are you ?

      </Text>

      <Text style={styles.text}>

        Hi, {‘n’} Welcome Here.

      </Text>

    </SafeAreaView>

  );

}

const styles = StyleSheet.create({

  MainContainer: {

    flex: 1,

  },

  text: {

    fontSize: 25,

    color: ‘black’,

    textAlign: ‘center’,

  }

});

Screenshot :-

Example of Insert Line Break on Text Component in React Native

Понравилась статья? Поделить с друзьями:
  • Word break keep all
  • Word break in english
  • Word break can i used to know
  • Word branch of knowledge
  • Word brain word picture