Nextjs Core Hooks

-
Pro Component


Since NextJS is server side rendered, and in some cases we needed to know the window size, or the type of browser, to better render some components, we’ve created the following two hooks (the second one is just for the PRO version)

Use Window Size

You will find its code inside components/Hooks/useWindowSize.js.

And this is how we’ve used it:

import React from "react";
...other code
// @material-ui/core components
...other code
// @material-ui/icons
...other code
// core components
...other code
import useWindowSize from "components/Hooks/useWindowSize.js";

...other code

export default function AdminNavbarLinks() {
  const size = useWindowSize();
  ...other code
  return (
    ...other code
      <Button
        color={size.width > 959 ? "transparent" : "white"}
        justIcon={size.width > 959}
        simple={!(size.width > 959)}
        aria-label="Dashboard"
        className={classes.buttonLink}
      >
        <Dashboard className={classes.icons} />
        <Hidden mdUp implementation="css">
          <p className={classes.linkText}>Dashboard</p>
        </Hidden>
      </Button>
      ...other code
  );
}

Use Navigator Platform pro

You will find its code inside components/Hooks/useNavigatorPlatform.js.

And this is how we’ve used it:

import React from "react";
...other code
import { useRouter } from "next/router";
// creates a beautiful scrollbar
import PerfectScrollbar from "perfect-scrollbar";
import "perfect-scrollbar/css/perfect-scrollbar.css";

// @material-ui/core components
...other code

// core components
...other code
import useNavigatorPlatform from "components/Hooks/useNavigatorPlatform.js";

...other code

export default function Dashboard(props) {
  ...other code
  // get type of navigator
  const navigatorPlatform = useNavigatorPlatform();
  // states and functions
  ...other code
  // ref for main panel div
  const mainPanel = React.createRef();
  // effect instead of componentDidMount, componentDidUpdate and componentWillUnmount
  React.useEffect(() => {
    if (navigator.platform.indexOf("Win") > -1) {
      ps = new PerfectScrollbar(mainPanel.current, {
        suppressScrollX: true,
        suppressScrollY: false,
      });
      document.body.style.overflow = "hidden";
    }
    window.addEventListener("resize", resizeFunction);

    // Specify how to clean up after this effect:
    return function cleanup() {
      if (navigator.platform.indexOf("Win") > -1) {
        ps.destroy();
      }
      window.removeEventListener("resize", resizeFunction);
    };
  });
  ...other code
  return (
    <div className={classes.wrapper}>
      ...other code
      <div className={mainPanelClasses} ref={mainPanel}>
        ...other code
      </div>
    </div>
  );
}