React hook to return configured device viewport type with help of a context provider
npm install react-viewport-hook``sh`
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.
#### Props
- 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;
#### Usage
When using it with client side or the server always renders the same viewport, you can use as:
`js
import { ViewportProvider } from 'react-viewport-hook';
const MainApp = () => (
);
`
When using with SSR:
`js
import { ViewportProvider } from 'react-viewport-hook';
const MainApp = () => (
);
`
When customizing the viewport types:
`js
import { ViewportProvider } from 'react-viewport-hook';
return (
viewportType: 'smallPhone',
minWith: 0,
maxWith: 199,
},
{
viewportType: 'others',
minWith: 200,
}
]>
);
`
This component reads the current viewport.
#### Usage
`js
import useViewportType from 'react-viewport-hook';
const AdaptativeComponent = () => {
const { viewportType, isPhone, isTablet, isDesktop } = useViewportType();
if (isPhone) {
return (
} else if (isTablet) {
return (
}
return (
}
`
`js
import useViewportType, { ViewportProvider } from 'react-viewport-hook';
const AdaptativeComponent = () => {
const { isPhone } = useViewportType();
return isPhone ?
}
const Component = () => (
);
`
`sh`
yarn install
`sh``
yarn build
- Add unit tests
- Upgrade to typescript
š¤ KennyPT
* Github: @KennyPT
Give a āļø if this project helped you!