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: |
---|---|
marginBox | top, right, bottom, left, width, height, x, y, center (x, y) |
borderBox | top, right, bottom, left, width, height, x, y, center (x, y) |
paddingBox | top, right, bottom, left, width, height, x, y, center (x, y) |
contentBox | top, right, bottom, left, width, height, x, y, center (x, y) |
border | top, right, bottom, left |
padding | top, right, bottom, left |
margin | top, 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 (<><Textarearef={elementRef}value="Resize this field's height, then either scroll or resize the page."/><Box>Changing height: {dimensions && dimensions.borderBox.height}</Box></>)}
Parameters#
Parameter | Type | Description |
---|---|---|
ref | RefObject<HTMLElement> | Reference to the element you want to measure |
observe (optional) | boolean | If set to true, the resize and scroll events will be attached to the window and update the dimensions on each event |