Hooks
useMediaQueryObject
Overview
useMediaQueryObject
hook handles scenarios in which you want to render component based on media query breakpoints.
This hooks also responds to the window resizing and returns the appropriate value for the new window size.
useMediaQueryObject
returns the value for the current breakpoint from the provided media query object ( MQ<T>
)
Note: The hook needs <MediaQueryProvider>
to be added to an ancestor of the component in which it's used.
Example
A common use case for using useMediaQueryObject
is when you want to change component property based on media query.
In the example below, the <Card />
component changes its layout depending on screen the size.
1const mqLayout = {
2 xs: 'vertical',
3 sm: 'vertical',
4 md: 'horizontal',
5 lg: 'horizontal',
6 xl: 'horizontal',
7}
8const layout = useMediaQueryObject(mqLayout);
9<Card layout={layout} />
Note: In theory useMediaQueryObject
could be used with any MQ<T>
, however, we recommend using it only for props that don't accept MQ<T>
as a value. Most CSS-based props and overrides already support MQ<T>
objects.
When you create your own components and want to apply responsive behaviour you should try to use getters and defaults functions.
DO NOT DO THIS:
1const stylePresets = {
2 xs: 'dividerPrimary',
3 md: 'horizontal',
4}
5const dividerStylePreset = useMediaQueryObject(stylePresets);
6<Divider overrides={{stylePreset: dividerStylePreset}} />
useBreakpointKey
Overview
useBreakpointKey
has a similar utility as useMediaQueryObject
, it's intended usage is where you want to know the currently active breakpoint key xs | sm | md | lg | xl
.
Example
1const breakpointKey = useBreakpointKey();
2// return XL when screen has width XL ( 1440px and above )
<Card />
component use case
1const breakpointKey = useBreakpointKey();
2 const layout == breakpointKey === 'xs || breakpointKey === 'sm' ? 'vertical' : 'horizontal';
3<Card layout={layout} />
4// the <Card will render verticaly on XS and SM screens and Horizontaly on the rest of breakpoints