Documentation
Feedback
Guides

Responsive Values

Utility for using props that accept different values for different devices or media queries.

For example, a given prop could accept both just a number...


_10
props: {
_10
quantity: 1,
_10
}

...or different values depending on the device or a media query:


_10
props: {
_10
quantity: {
_10
mobile: 1,
_10
desktop: 2,
_10
'(min-width: 1500px)': 4,
_10
}
_10
}

...and the component, in turn, would use it like this:


_15
import { useResponsiveValue } from 'vtex.responsive-values'
_15
_15
const MyComponent = ({ quantity }) => {
_15
const quantity = useResponsiveValue(quantity)
_15
_15
return <span>{quantity}</span>
_15
}
_15
_15
<MyComponent quantity={1} /> {/* always returns 1 */}
_15
_15
<MyComponent quantity={{
_15
'(min-width: 1500px)': 4,
_15
desktop: 2,
_15
mobile: 1,
_15
}} /> {/* returns 1 on mobile devices, 2 on desktop */}

Alternately, if you want to apply it to multiple values at once, or even the entire props object, you can use the hook useResponsiveValues (notice the plural) hook.


_29
import { useResponsiveValues } from 'vtex.responsive-values'
_29
_29
const MyComponent = props => {
_29
const { margin, padding } = useResponsiveValues(
_29
{
_29
margin: props.margin,
_29
padding: props.padding
_29
}
_29
)
_29
_29
return (
_29
<section style={{ margin, padding }}>
_29
<span>{props.children}</span>
_29
</section>
_29
)
_29
}
_29
_29
<MyComponent margin={4} padding={4} /> {/* always returns margin 4 / padding 4 */}
_29
_29
<MyComponent
_29
margin={{
_29
desktop: 4,
_29
mobile: 2,
_29
}}
_29
padding={{
_29
desktop: 4,
_29
mobile: 2,
_29
}}
_29
/> {/* returns 1 on mobile devices, 2 on desktop */}

There are some things to keep in mind when using media queries:

  • Media queries take precedence over devices. If one matches, any device-specific value is ignored.
  • Media queries are written following the standard media query syntax.
  • The definiton order matters. If more than one media query is matched, the first matched one is used.

API

Props that use this hook accept either a value by itself, or an object with the following options: phone and tablet separately (or just mobile for both), desktop and generic media queries.

If there is any missing device, it will fallback to the next largest one. For example, if only the values of phone and desktop are passed, tablet devices will receive the value from desktop. Media queries have no fallback behavior.

Contributors
2
Photo of the contributor
Photo of the contributor
+ 2 contributors
Was this helpful?
Yes
No
Suggest edits (Github)
Contributors
2
Photo of the contributor
Photo of the contributor
+ 2 contributors
On this page