React native text word break strategy of strings with dash

Viewed 12725

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.

3 Answers

Use unicode \u2011 of non breaking hyphen in string. So, for your example it would look like this:

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

Didn't find any CSS trick for this. But you can use regx for shortcut. just add a new line before any hyphenated words. it is not a perfect solution but at least for this kind of situation this will work

        export default class App extends Component {
        constructor(props) {
        super(props);

         this.processString = this.processString.bind(this);
        }

         processString() {
         const regex = /((\w+\-(.*?)\w+)\s)/gm;
         const str = `This is a sample of text-with-dash incorrectly word breaking`;
         const subst = `\n$1`;
         const result = str.replace(regex, subst);
         return result;
        }

         render() {
             return (
                  <View style={styles.container}>
          <TouchableOpacity style={{ width: 250, backgroundColor: 
        "skyblue" 
         }}>
          <Text style={styles.welcome}>{this.processString()}</Text>
           </TouchableOpacity>
          </View>
          );
           }
         }
Related