timzaak
timzaak

Reputation: 43

How to get text size or view size before rendering in React Native

I have found UIManager and onLayout, but all of them can get only the size after rendering. Are there any 3rd party libraries or APIs to do this before rendering?

The Image component has something like:

var image = new Image();
image.src="??"
image.onload(()=>image.height)

But how about getting the dimensions of a Text or a View?

Upvotes: 4

Views: 13348

Answers (3)

Kartikey
Kartikey

Reputation: 5002

I think this would help you. From here you can get the Dimensionn of the view.

Upvotes: 2

Saeed Zhiany
Saeed Zhiany

Reputation: 2141

If you are still looking for a solution, I suggest using react-native-text-size. it allows you to get text dimensions before rendering it by using async functions. here is an example of how to use it to achieve what you need.

import rnTextSize, { TSFontSpecs } from 'react-native-text-size'

type Props = {}
type State = { width: number, height: number }

// On iOS 9+ will show 'San Francisco' and 'Roboto' on Android
const fontSpecs: TSFontSpecs = {
  fontFamily = undefined,
  fontSize = 24,
  fontStyle = 'italic',
  fontWeight = 'bold',
}
const text = 'I ❤️ rnTextSize'

class Test extends Component<Props, State> {
  state = {
    width: 0,
    height: 0,
  }

  async componentDidMount() {
    const width = Dimensions.get('window').width * 0.8
    const size = await rnTextSize.measure({
      text,             // text to measure, can include symbols
      width,            // max-width of the "virtual" container
      ...fontSpecs,     // RN font specification
    })
    this.setState({
      width: size.width,
      height: size.height
    })
  }

  // The result is reversible
  render() {
    const { width, height } = this.state
    return (
      <View style={{ padding: 12 }}>
        <Text style={{ width, height, ...fontSpecs }}>
          {text}
        </Text>
      </View>
    )
  }
}

Upvotes: 1

Martin Cup
Martin Cup

Reputation: 2582

I don't know if this is possible. But as a workaround you could make the elements invisible by changing their colors or opacity, then calculate the dimensions, then make some changes etc. and then make it visible.

Upvotes: 1

Related Questions