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.