useDimensions

useDimensions is a custom hook that measures dimensions of the referenced element based on its box-model.

Import#

import { useDimensions } from '@chakra-ui/react'

Return value#

This hook returns an object with the properties marginBox, paddingBox, borderBox, contentBox, border, padding, and margin.

Each of these properties contains a nested object which provides values respective to that property:

Value:Contents:
marginBoxtop, right, bottom, left, width, height, x, y, center (x, y)
borderBoxtop, right, bottom, left, width, height, x, y, center (x, y)
paddingBoxtop, right, bottom, left, width, height, x, y, center (x, y)
contentBoxtop, right, bottom, left, width, height, x, y, center (x, y)
bordertop, right, bottom, left
paddingtop, right, bottom, left
margintop, right, bottom, left

Usage#

function example() {
const elementRef = useRef()
const dimensions = useDimensions(elementRef)
return (
<Box ref={elementRef} color='white' width='fit-content' bg='blue.700' p={4}>
<Heading>
<code>borderBox</code> dimensions
</Heading>
<List>
<ListItem>
The Width: {dimensions && dimensions.borderBox.width}
</ListItem>
<ListItem>
The x coordinate: {dimensions && dimensions.borderBox.x}
</ListItem>
</List>
</Box>
)
}

With observe Parameter#

With the second parameter set to true, the hook will attach the resize and scroll events to the window object. This will recalculate the reference element's dimensions on scroll or resize of the page.

function example() {
const elementRef = useRef()
const dimensions = useDimensions(elementRef, true)
return (
<>
<Textarea
ref={elementRef}
value="Resize this field's height, then either scroll or resize the page."
/>
<Box>Changing height: {dimensions && dimensions.borderBox.height}</Box>
</>
)
}

Parameters#

ParameterTypeDescription
refRefObject<HTMLElement>Reference to the element you want to measure
observe (optional)booleanIf set to true, the resize and scroll events will be attached to the window and update the dimensions on each event

Proudly made inNigeria by Segun Adebayo

Deployed by â–² Vercel