How to set and unset a body zoom level in React

Viewed 4189

I am writing a react application in which I need to set the zoom level of a particular page to 90%. I know that I can do it using document.body.style.zoom = '90%' as given below:

useEffect(() => {
    document.body.style.zoom = "90%";
  }, []);

It's a basic componentDidMount function in react using useEffect. But the problem is how to set the zoom level back to the default as it was before loading the page using componentDidUnmount?

1 Answers

Add cleanup effect as callback returned from useEffect.

The clean-up function runs before the component is removed from the UI to prevent memory leaks.

const Zoom = () => {
  useEffect(() => {
    const initialValue = document.body.style.zoom;

    // Change zoom level on mount
    document.body.style.zoom = "150%";

    return () => {
      // Restore default value
      document.body.style.zoom = initialValue;
    };
  }, []);
  return <></>;
};

Such callback acts like componentWillUnmount.

Edit confident-williams-izk82

Related