Responsively hiding components

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:

  1. First, we have to install the @rehooks/window-size library:
> npm install --save @rehooks/window-size
  1. Then, we import the useWindowSize Hook at the start of the src/pages/HeaderBar.js file:
import useWindowSize from '@rehooks/window-size'
  1. Next, we define the following Window Size Hook after the existing Context Hooks:
            const { innerWidth } = useWindowSize()
  1. If the window width is smaller than 640 pixels, we assume that the device is a mobile phone:
            const mobilePhone = innerWidth < 640
  1. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.199.243