Reputation: 921
I'm working on an app with React Native.
I have a "Card" component that display Text elements, which can have any amount of characters.
So right now I'm trying to set a dynamic height for my card. My idea is to set a certain height if the amount of lines is 1, a larger height if the amount of lines is 2, and a larger one if it's 3 or more (truncating the text with ellipsis).
Is there any way I can get the amount of lines the takes, so I can determine which height I should use?
An option would be to do it based on the amount of characters, but that wouldn't work properly in different sized devices.
I feel this is something easy and there's a common way to do it, but I can't seem to realize how to implement it.
Thanks!
Upvotes: 0
Views: 1298
Reputation: 544
this is my solution. it work perfect on android
const [textLength, setTextLength] = useState(0);
const onTextLayout = useCallback(e => {
setTextLength(e.nativeEvent.lines.length);
}, []);
return (
<Text onTextLayout={onTextLayout}>
{SOME_TEXT_BLOCK}
</Text>
);
Upvotes: 1
Reputation: 620
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')
}} />
Upvotes: 4