Return to Sky UI homepage

useResponsiveProps

import { useResponsiveProps } from '@sky-uk/ui-core';

The useResponsiveProps hook can be used to makes props respond to different screen sizes.

Basic usage

() => {
const Example = ({ message: _message }) => {
const { message } = useResponsiveProps({ message: _message });
return <div>{message}</div>;
}
return <Example message={{ xs: 'goodbye', lg: 'hello' }} />;
}

With multiple props

() => {
const Example = ({ message: _message, message2: _message2, size: _size }) => {
const { message, message2, size } = useResponsiveProps({ message: _message, message2: _message2, size: _size });
return (<ol>
<li>{message}</li>
<li>{message2}</li>
<li>{size}</li>
</ol>);
}
return <Example
message={{
xs: 'goodbye',
lg: 'hello'
}}
message2={{
xs: 'hello',
md: 'goodbye'
}}
size={{
xs: 'x-small',
md: 'medium',
xl: 'x-large'
}}
/>;
}

Use with asset URLs

When using this hook to switch between asset URLs, if modifying the URL (e.g. to add query params) then you will need to guard against the hook's initial undefined return, to avoid unwanted network requests:

() => {
const Example = ({src: _src}) => {
const { src } = useResponsiveProps({ src: _src });
return <div>
{/* Without the guard below, a request will be made for `undefined?text=hello` */}
{src && <img alt="" src={`${src}?text=hello`} />}
</div>;
}
return <Example src={{ xs: 'http://placehold.it/50/50', lg: 'http://placehold.it/100/100' }} />;
}

You do not need to guard against the above if using the asset URL returned from the hook "as-is", because React will just omit the src attribute altogether when given undefined.