React native text word break strategy of strings with dash

hdsenevi picture hdsenevi · Nov 13, 2018 · Viewed 9.4k times · Source

Setup

react: 16.6.0-alpha.8af6728
react-native: 0.57.4

Problem

Word breaking in Text component does not handle strings with dashes the way app design wants it. I want to word wrap the whole word taking into account dashes. This whole string-with-dashes should be considered a word when word wrapping. But flexbox does not.

Code

<TouchableOpacity style={{ width: 250, backgroundColor: 'skyblue' }}>
    <Text style={styles.welcome}>This is a sample of text-with-dash incorrectly word breaking</Text>
</TouchableOpacity>

Restult looks like this:

enter image description here

But I want it to end up like this (text-with-dash on a seperate line):

enter image description here

The issue is I get the strings from an online CMS and want a flexbox styling solution to this problem. There might be situation where a string-with-dash could end up in a single line so in those instances I don't want a word wrap of cause.

Answer

Chong Zheng picture Chong Zheng · May 28, 2019

You can now use the textbreakstrategy as props of Text.

By default, the text break strategy is 'highQuality' which breaks the words and appends the '-' for those words.

Use 'simple' in the textbreakstrategy to avoid the '-' when breaking words.

For example:

<Text textBreakStrategy={'simple'}>
This is a sample of text-with-dash incorrectly word breaking
</Text>

Additional Reference: https://developer.android.com/reference/android/text/Layout.html#BREAK_STRATEGY_SIMPLE