How to show see more in React Native Web

Viewed 562

How do I do the "see more" in react native web? My problem is on the onLayout and onTextLayout. How do I determine to show the "see more" if its too long?

const ReadMoreText = () => {
  const [textShown, setTextShown] = useState(false) //To show ur remaining Text
  const [lengthMore, setLengthMore] = useState(false) //to show the "Read more & Less Line"
  const toggleNumberOfLines = () => {
    //To toggle the show text or hide it
    setTextShown(!textShown)
  }

  const onTextLayout = useCallback((e) => {
    // setLengthMore(e.nativeEvent.lines.length >= 4) //to check the text is more than 4 lines or not
    // console.log(e.nativeEvent);
  }, [])

  return (
    <View style={styles.mainContainer}>
      <Text
        onLayout={onTextLayout}
        numberOfLines={textShown ? undefined : 4}
      >
        SAMPLE TEXT HERE...
      </Text>

      {lengthMore ? (
        <Text
          onPress={toggleNumberOfLines}
        >
          {textShown ? 'Read less...' : 'Read more...'}
        </Text>
      ) : null}
    </View>
  )
}
1 Answers

I spent a long time looking into this and my solution was to implement a really simple component (below) which just limits the lines and allows you to show more. Maybe this is enough for you.

If not you could create a ref and use measureInWindow to get the measurement of the text container. ref.measureInWindow((x, y, width, height) => {})

import * as React from 'react'
import { Text } from 'react-native'

export default function ReadMore({ children, numLines = 4, style }) {
  const [lines, setLines] = React.useState(numLines)

  return (
    <>
      <Text numberOfLines={lines} style={style}>
        {children}
      </Text>
      {lines === 0 ? (
        <Text onPress={() => setLines(numLines)} style={{fontWeight:'bold'}}>
          Read Less
        </Text>
      ) : (
        <Text onPress={() => setLines(0)} style={{fontWeight:'bold'}}>
          Read More
        </Text>
      )}
    </>
  )
}
Related