6

I have a problem, in react-native, I want to know if it's possible to know if the text is overflowing a container, imagine the following code(Container can be anything, View, ScrollView, etc doesn't matter)

<Container>
 <Text> Long text...</Text>
</Container>
{textOverflows && <GradientComponent/>}

Basically I am trying to have a boolean if the text overflows and conditionally add a gradient on the bottom of the container if needed.

nomadSK25
  • 2,350
  • 3
  • 25
  • 36
r00t -
  • 225
  • 1
  • 2
  • 12
  • You can create a in-memory element and check its width. If the width of this element is greater than container's width, its overflowing. Useful [reference](https://stackoverflow.com/a/18789962/3783478) – Rajesh Dec 10 '19 at 14:05
  • That commented link is for creating a HTML DOM element in a browser and doesn't apply to React Native. – user56reinstatemonica8 Feb 16 '21 at 15:00

2 Answers2

0

Using the suggestion of @Rajesh in the comment, we can use a dummy Text component to measure the text length. Here is a simple example (link to Expo Snack), where typing in the TextInput leads to the display of the width (NOT the number of characters) of the text in the current layout. The width of a text container can be obtained similarly via onLayout or computed based on flex. Then we only need to compare the text width with the container width to determine whether there is overflow.

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

const MyComponent = props => {
  const [text, setText] = React.useState('');
  const [textWidth, setTextWidth] = React.useState(0);

  return (
    <View style={{top: 200}}>
      <TextInput
        style={{borderWidth: 1, borderColor: 'black', height: 30}}
        onChangeText={text => setText(text)}
        placeholder="Type something"
      />
      {/* dummy text to acquire text width. Hide it according to the current layout*/}
      <View
        style={{height: 0, alignSelf: 'flex-start'}}
        onLayout={e => {
          setTextWidth(e.nativeEvent.layout.width);
        }}>
        <Text style={{color: 'white'}}>{text}</Text>
      </View>
      <View>
        <Text>{`Text width: ${textWidth}`}</Text>
      </View>
    </View>
  );
};

export default MyComponent

NOTE: setting the dummy text container style alignSelf is a crucial step, because it forces the dummy text container to wrap the text tightly. Otherwise, the dummy text container width will always be the maximum width of the screen. See this answer for more details.

Fanchen Bao
  • 3,310
  • 1
  • 21
  • 34
-4

What you can do is check the length of that text and if the length of the text is longer than the width of that container add style to it. It wull look something like this:

text.legth >container.width ? style= {styles.gradientCompoennt} : style={styles.whatever}

kodak
  • 81
  • 11