yarn add react-viewport-hook
React hook and context provider to give the current defined viewport type based on the current device screen size or when there is a screen resize. This is useful for scenarios like adaptative react pages where we want to render different components for different viewports and CSS is not a good option (like a dropdown for desktop and a modal for phone).
By default this works with the viewport types:
phone
: from 0px to 479px;tablet
: from 480px to 767px;desktop
: from 768px;But you can customize the viewports to use on the provider component.
This component updates the viewport type when the screen hits a viewport breakpoint.
Important! Your app should only have one viewport provider on the react tree.
initialViewportType
: desktop by default, this is useful when using it with SSR (server side rendering) and we want to initially use a viewport type based not on the screen size but on the user agent;customViewportTypes
: list of custom viewport types;children
: app component;When using it with client side or the server always renders the same viewport, you can use as:
import { ViewportProvider } from 'react-viewport-hook';
const MainApp = () => (
<ViewportProvider>
<App />
</ViewportProvider>
);
When using with SSR:
import { ViewportProvider } from 'react-viewport-hook';
const MainApp = () => (
<ViewportProvider initialViewportType={serverViewportBasedOnUserAgent}>
<App />
</ViewportProvider>
);
When customizing the viewport types:
import { ViewportProvider } from 'react-viewport-hook';
return (
<ViewportProvider customViewportTypes={[
{
viewportType: 'smallPhone',
minWith: 0,
maxWith: 199,
},
{
viewportType: 'others',
minWith: 200,
}
]>
<App />
</ViewportProvider>
);
This component reads the current viewport.
import useViewportType from 'react-viewport-hook';
const AdaptativeComponent = () => {
const { viewportType, isPhone, isTablet, isDesktop } = useViewportType();
if (isPhone) {
return (<PhoneComponent />);
} else if (isTablet) {
return (<TabletComponent />);
}
return (<DesktopComponent />);
}
import useViewportType, { ViewportProvider } from 'react-viewport-hook';
const AdaptativeComponent = () => {
const { isPhone } = useViewportType();
return isPhone ? <PhoneComponent /> : <DesktopComponent />;
}
const Component = () => (
<ViewportProvider>
<AdaptativeComponent />
</ViewportProvider>
);
yarn install
yarn build
👤 KennyPT ricardo.rocha.pinheiro@gmail.com
Give a ⭐️ if this project helped you!