Categories
React Answers

How to Prevent Scrolling Using CSS on React Rendered Components?

Spread the love

Sometimes, we want to prevent scrolling using CSS on React rendered components.

In this article, we’ll look at how to prevent scrolling using CSS on React rendered components.

Prevent Scrolling Using CSS on React Rendered Components

To prevent scrolling using CSS on React rendered components, we can set the overflow CSS property to hidden with JavaScript.

For instance, we write:

import React, { useEffect } from "react";

export default function App() {
  useEffect(() => {
    document.body.style.overflow = "hidden";
  }, []);

  return <div>hello world</div>;
}

to set the overflow CSS of the body element to hidden when the component mounts with:

document.body.style.overflow = "hidden";

The useEffect callback only runs when the component mounts since we passed in an empty array as the 2nd argument of useEffect.

Conclusion

To prevent scrolling using CSS on React rendered components, we can set the overflow CSS property to hidden with JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *