React useBodyScrollLock Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to implement the useBodyScrollLock() hook in a React application. This hook allows us to disable scrolling on the body element of a webpage while a modal or other overlay is open. By using this hook, we can prevent users from accidentally scrolling away from the content they are trying to interact with.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react(("`React`")) -.-> react/StylingGroup(["`Styling`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") react/StylingGroup -.-> react/css_in_react("`CSS in React`") subgraph Lab Skills react/jsx -.-> lab-38371{{"`React useBodyScrollLock Hook`"}} react/event_handling -.-> lab-38371{{"`React useBodyScrollLock Hook`"}} react/hooks -.-> lab-38371{{"`React useBodyScrollLock Hook`"}} react/use_state_reducer -.-> lab-38371{{"`React useBodyScrollLock Hook`"}} react/css_in_react -.-> lab-38371{{"`React useBodyScrollLock Hook`"}} end

React useBodyScrollLock Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

This code snippet allows users to lock the body scroll when a modal is open. Here's how it works:

First, the useBodyScrollLock function is defined, which uses the useLayoutEffect hook to lock the scroll of the body element. This hook runs only once when the component is mounted, and it sets the overflow value of the body element to 'hidden'. When the component is unmounted, the original overflow value is restored.

const useBodyScrollLock = () => {
  React.useLayoutEffect(() => {
    const originalStyle = window.getComputedStyle(document.body).overflow;
    document.body.style.overflow = "hidden";
    return () => (document.body.style.overflow = originalStyle);
  }, []);
};

Then, the Modal component is defined, which utilizes the useBodyScrollLock function. This component displays a message in a box that is centered on the screen. When the box is clicked, the modal is closed and the body scroll is unlocked.

const Modal = ({ onClose }) => {
  useBodyScrollLock();

  return (
    <div
      style={{
        zIndex: 100,
        background: "rgba(0,0,0,0.25)",
        display: "flex",
        justifyContent: "center",
        alignItems: "center"
      }}
      onClick={onClose}
    >
      <p style={{ padding: 8, borderRadius: 8, background: "#fff" }}>
        Scroll locked! <br /> Click me to unlock
      </p>
    </div>
  );
};

Finally, the MyApp component is defined, which renders a button that opens the Modal component when clicked.

const MyApp = () => {
  const [modalOpen, setModalOpen] = React.useState(false);

  return (
    <div
      style={{
        height: "400vh",
        textAlign: "center",
        paddingTop: 100,
        background: "linear-gradient(to bottom, #1fa2ff, #12d8fa, #a6ffcb)"
      }}
    >
      <button onClick={() => setModalOpen(true)}>Open modal</button>
      {modalOpen && <Modal onClose={() => setModalOpen(false)} />}
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<MyApp />);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the React useBodyScrollLock Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like