1

I have an issue where amounts of text (in my case a ToS) is not rendering properly onto the screen (this occurs when the string makes the text field larger than a height of 8000). I've read the solution to the problem is to split the ToS into multiple text tags.

How could I go about splitting the string at every new line and programatically generating a text tag for it?

for example:

"paragraph1...

paragraph2...."

into:

<Text>paragraph1...</Text>
<Text>paragraph1...</Text>

2 Answers 2

4

This is untested, but I did something similar in an app I built.

The principle is that you loop through your text string and split it into chunks of whatever desired length, wrapping each chunk in it's own <Text> element and appending it to an array.

Edit: Alternatively, you could modify this function to split the string on newline character instead of a specific length.

import { Text } from 'react-native';

export function split(string, length = 1000) {
  // Split text into individual words and count length
  const words = string.split(' ');
  const count = words.length;

  // Prepare elements and position tracker
  const elements = [];
  let position = 0;

  // Loop through words whilst position is less than count
  while (position < count) {
    // Prepare text for specified length and increment position
    const text = words.slice(position, length).join(' ');
    position += length;

    // Append text element
    elements.push((
      <Text>{text}</Text>
    ));
  }

  return elements;
}
Sign up to request clarification or add additional context in comments.

2 Comments

For people reading this answer, elements and position can't be constants as their values are changing in the while loop. They should be variables (let or var).
Good call on the position being declared as let. The elements can remain const, because the variable stores the reference to the object, not the actual object, so never actually changes.
0

You could look at react-native-parsed-text (https://github.com/taskrabbit/react-native-parsed-text)

It might be a bit more than you need, but you can easily match on the newline character and render a new component for each line

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.