最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set and unset a body zoom level in React - Stack Overflow

programmeradmin7浏览0评论

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 ponentDidMount 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 ponentDidUnmount?

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 ponentDidMount 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 ponentDidUnmount?

Share Improve this question edited Jun 7, 2020 at 17:36 Dennis Vash 54k12 gold badges117 silver badges132 bronze badges asked Jun 7, 2020 at 17:21 Vimal Kurien SamVimal Kurien Sam 2661 gold badge5 silver badges11 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

Add cleanup effect as callback returned from useEffect.

The clean-up function runs before the ponent 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 ponentWillUnmount.

发布评论

评论列表(0)

  1. 暂无评论