In our blog app, we are going to hide the UserBar and ChangeTheme components completely when the screen size is very small so that, when reading a post on a mobile phone, we can focus on the content.
Let's get started implementing the Window Size Hook:
- First, we have to install the @rehooks/window-size library:
> npm install --save @rehooks/window-size
- Then, we import the useWindowSize Hook at the start of the src/pages/HeaderBar.js file:
import useWindowSize from '@rehooks/window-size'
- Next, we define the following Window Size Hook after the existing Context Hooks:
const { innerWidth } = useWindowSize()
- If the window width is smaller than 640 pixels, we assume that the device is a mobile phone:
const mobilePhone = innerWidth < 640
- Finally, we only show the ChangeTheme and UserBar components when we are not on a mobile phone:
{!mobilePhone && <ChangeTheme theme={theme} setTheme={setTheme} />}
{!mobilePhone && <br />}
{!mobilePhone && <React.Suspense fallback={"Loading..."}>
<UserBar />
</React.Suspense>}
{!mobilePhone && <br />}
If we now resize our browser window to a width smaller than 640 pixels, we can see that the ChangeTheme and UserBar components will not be rendered anymore:
Hiding the ChangeTheme and UserBar components on smaller screen sizes
Using the Window Size Hook, we can avoid rendering elements on smaller screen sizes.