React Native: Determine Number of Lines of Text Component

How can I get the number of lines of Text component in React Native?

In current version this feature is not available in RN, But there is the best library you can use
react-native-read-more-text which will give results as you want.

React native text component using number of lines

You can use numberOfLines as a props for <Text /> component. Its depend on the width of your component then calculate the length of the text. This prop is commonly used with ellipsizeMode.
Example:

<Text numberOfLines={2} ellipsizeMode='tail'>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</Text>

Get amount of lines from Text component

One immediate solution is to get the compiled height of text input and divide it by line height you have set in styles.

<Text onLayout={(event) => {
const {height} = event.nativeEvent.layout;
const lineHeight = 14;
console.log('my text has'+ height/lineHeight +' lines')
}} />

How to get the current number of lines in String of TextInput?

As far as I know, there is no offical way to get the currently used number of lines, but I have a workaround for you:

We make use of the onLayout method of our TextInput and we keep track of the currently used height. We need two state variables:

this.state = {
height: 0, // here we track the currently used height
usedLines: 0,// here we calculate the currently used lines
}

onLayout:

  _onLayout(e) {
console.log('e', e.nativeEvent.layout.height);
// the height increased therefore we also increase the usedLine counter
if (this.state.height < e.nativeEvent.layout.height) {
this.setState({usedLines: this.state.usedLines+1});
}
// the height decreased, we subtract a line from the line counter
if (this.state.height > e.nativeEvent.layout.height){
this.setState({usedLines: this.state.usedLines-1});
}
// update height if necessary
if (this.state.height != e.nativeEvent.layout.height){
this.setState({height: e.nativeEvent.layout.height});
}

}

Render Method

  render() {
console.log('usedLines', this.state.usedLines);
return (
<View style={styles.container}>
<TextInput multiline style={{backgroundColor: 'green'}} onLayout={(e)=> this._onLayout(e)} />
</View>
);
}

Working Example:

https://snack.expo.io/B1vC8dvJH

how numberOfLines work in react native Text component?

It will show your content in <Text> component which is fitted in those numberOfLines.

With output you are expecting or want to perform, you can use dynamic numberOfLines using state.

Just have that state variable default value of lineNumbers and change it when pressing on button or any other component.

this.state = {
lineNumbers: 2
}

This indicates your numberOfLines will be default 2, and once user press on button or read more

this.setState({lineNumbers: null})

It will show whole content.

<Text numberOfLines={this.state.lineNumbers}>


Related Topics



Leave a reply



Submit