You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DimensionsDetector.native.tsx 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import React, { useCallback, useEffect } from 'react';
  2. import { StyleSheet, View } from 'react-native';
  3. import { useSafeAreaInsets } from 'react-native-safe-area-context';
  4. interface IProps {
  5. /**
  6. * Any nested components.
  7. */
  8. children: React.ReactNode;
  9. /**
  10. * The "onLayout" handler.
  11. */
  12. onDimensionsChanged?: Function;
  13. /**
  14. * The safe are insets handler.
  15. */
  16. onSafeAreaInsetsChanged?: Function;
  17. }
  18. /**
  19. * A {@link View} which captures the 'onLayout' event and calls a prop with the
  20. * component size.
  21. *
  22. * @param {IProps} props - The read-only properties with which the new
  23. * instance is to be initialized.
  24. * @returns {Component} - Renders the root view and it's children.
  25. */
  26. export default function DimensionsDetector(props: IProps) {
  27. const { top = 0, right = 0, bottom = 0, left = 0 } = useSafeAreaInsets();
  28. const { children, onDimensionsChanged, onSafeAreaInsetsChanged } = props;
  29. useEffect(() => {
  30. onSafeAreaInsetsChanged?.({
  31. top,
  32. right,
  33. bottom,
  34. left
  35. });
  36. }, [ onSafeAreaInsetsChanged, top, right, bottom, left ]);
  37. /**
  38. * Handles the "on layout" View's event and calls the onDimensionsChanged
  39. * prop.
  40. *
  41. * @param {Object} event - The "on layout" event object/structure passed
  42. * by react-native.
  43. * @private
  44. * @returns {void}
  45. */
  46. const onLayout = useCallback(({ nativeEvent: { layout: { height, width } } }) => {
  47. onDimensionsChanged?.(width, height);
  48. }, [ onDimensionsChanged ]);
  49. return (
  50. <View
  51. onLayout = { onLayout }
  52. style = { StyleSheet.absoluteFillObject } >
  53. { children }
  54. </View>
  55. );
  56. }