How to get the size of a View in React Native?

Sometimes, we want to get the size of a View in React Native.

In this article, we’ll look at how to get the size of a View in React Native.

How to get the size of a View in React Native?

To get the size of a View in React Native, we can get them from the parameter of the onLayout callback.

For instance, we write:

import * as React from 'react';
import { View, StyleSheet } from 'react-native';
import { Text } from 'react-native-paper';

const MyComponent = () => {
  const [dims, setDims] = React.useState({});
  return (
    <View
      onLayout={(event) => {
        const { x, y, width, height } = event.nativeEvent.layout;
        setDims({ x, y, width, height });
      }}>
      <Text>{JSON.stringify(dims)}</Text>
    </View>
  );
};

export default MyComponent;

to set onLayout prop of the View to a function that gets the x, y, width and height properties from event.nativeEvent.layout.

x and y are the coordinates of the top left corner of the View.

width and height are its width and height.

Conclusion

To get the size of a View in React Native, we can get them from the parameter of the onLayout callback.