Skip to content

Instantly share code, notes, and snippets.

@sturmenta
Last active December 17, 2023 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sturmenta/2bf6fa1e58d30c5977810b737c6173c0 to your computer and use it in GitHub Desktop.
Save sturmenta/2bf6fa1e58d30c5977810b737c6173c0 to your computer and use it in GitHub Desktop.
react native - get the father component dimensions
import React, { useState } from "react"
import { View, ViewProps } from "react-native"
interface ContainerWithDimensionsProps {
children: ({
width,
height
}: {
width: number
height: number
}) => React.ReactNode
viewProps?: ViewProps
}
export const ContainerWithDimensions: React.FC<
ContainerWithDimensionsProps
> = ({ children, viewProps }: ContainerWithDimensionsProps) => {
const [dimensions, setDimensions] = useState({ width: 0, height: 0 })
return (
<View
onLayout={(event) =>
setDimensions({
width: event.nativeEvent.layout.width,
height: event.nativeEvent.layout.height
})
}
{...viewProps}>
{children(dimensions)}
</View>
)
}
// ────────────────────────────────────────────────────────────────────────────────
// usage
// <ContainerWithDimensions viewProps={{style: {}}}>
// {({width, height}) => {
// console.log('width', width);
// console.log('height', height);
// return <View />;
// }}
// </ContainerWithDimensions>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment