ReONE-SM1975 / nobel_prizes_SM1975

A web app to search nobel prizes winner - enhanced via django and reactJS
MIT License
1 stars 0 forks source link

create components to detect window height and width #43

Open SirrorsMoore1975 opened 4 months ago

SirrorsMoore1975 commented 4 months ago

create a components that can detect the height and width of the current windows that uses that components. For example, if this component is called in the header, the component should return the current width and height of the current window. It should also update the width and height when the screen size is updated.

Consider tutorial such as :-

From those website, it seems that you can obtain current windows height via windowInnerWidth and windowInnerHeight. Change anything necessary to fit the case :-

import { useRef } from 'react';

export default function App() {
  const windowSize = useRef([window.innerWidth, window.innerHeight]);

  return (
    <div>
      <h2>Width: {windowSize.current[0]}</h2>

      <h2>Height: {windowSize.current[1]}</h2>
    </div>
  );
}

For resizing the windows:-

import { useState, useEffect } from 'react';

export default function App() {
  const [windowSize, setWindowSize] = useState([
    window.innerWidth,
    window.innerHeight,
  ]);

  useEffect(() => {
    const handleWindowResize = () => {
      setWindowSize([window.innerWidth, window.innerHeight]);
    };

    window.addEventListener('resize', handleWindowResize);

    return () => {
      window.removeEventListener('resize', handleWindowResize);
    };
  }, []);

  return (
    <div>
      <h2>Width: {windowSize[0]}</h2>

      <h2>Height: {windowSize[1]}</h2>
    </div>
  );
}

We use the useState React hook to create a state variable that will be updated whenever the height or width of the window changes.

The useState hook returns an array of two values. This first is a variable that stores the state, and the second is a function that updates the state when it is called.

 const [windowSize, setWindowSize] = useState([
    window.innerWidth,
    window.innerHeight,
  ]);

The useEffect hook is used to perform an action when a component first renders, and when one or more specified dependencies change. In our example, the action is to add the event listener for the resize hook with the addEventListener() method.

We pass an empty dependencies array to the useEffect, so that it gets called only once in the component's lifetime, and the resize event listener is only registered once - when the component first renders.

 useEffect(() => {
    const handleWindowResize = () => {
      setWindowSize([window.innerWidth, window.innerHeight]);
    };

    window.addEventListener('resize', handleWindowResize);

    return () => {
      window.removeEventListener('resize', handleWindowResize);
    };
  }, []);

In the resize event listener, we update the state variable with the new height and width of the window.

The function we return in useEffect is a function that performs clean-up operations in the component. We use the removeEventListener() method to remove the resize event listener in this clean-up function and prevent a memory leak.

SirrorsMoore1975 commented 4 months ago

Here's an example of a React component that can track the current width and height of the screen, and update the values when the screen is resized. This component can be adjusted according to the page setting:

import React, { useState, useEffect } from 'react';

const ScreenSizeTracker = ({ width, height, onResize }) => {
  const [screenWidth, setScreenWidth] = useState(width || window.innerWidth);
  const [screenHeight, setScreenHeight] = useState(height || window.innerHeight);

  useEffect(() => {
    const handleResize = () => {
      setScreenWidth(window.innerWidth);
      setScreenHeight(window.innerHeight);
      if (typeof onResize === 'function') {
        onResize({ width: window.innerWidth, height: window.innerHeight });
      }
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [onResize]);

  return (
    <div>
      <p>Screen width: {screenWidth} px</p>
      <p>Screen height: {screenHeight} px</p>
    </div>
  );
};

export default ScreenSizeTracker;

Here's how this component works:

  1. The component takes in two optional props: width and height. If these props are provided, they will be used as the initial values for the screen size. Otherwise, the component will use the current window size.
  2. The component uses the useState hook to store the current screen width and height. These values are updated whenever the window is resized.
  3. The useEffect hook is used to set up an event listener for the resize event on the window. When the window is resized, the event handler updates the screen width and height state variables, and also calls the onResize callback function (if provided) with the new screen size.
  4. The onResize callback function is an optional prop that can be used to perform additional actions when the screen size changes (e.g., updating the layout of the page).
  5. The component renders a simple div element that displays the current screen width and height.

You can use this component in your React app like this:

import ScreenSizeTracker from './ScreenSizeTracker';

const MyPage = () => {
  const handleResize = (size) => {
    console.log(`Screen size changed to ${size.width}x${size.height}`);
    // Perform additional actions here, such as updating the layout
  };

  return (
    <div>
      <h1>My Page</h1>
      <ScreenSizeTracker onResize={handleResize} />
      {/* Other page content */}
    </div>
  );
};

export default MyPage;

In this example, the ScreenSizeTracker component is used within the MyPage component. Whenever the screen size changes, the handleResize function is called, which logs the new size to the console and can be used to update the layout of the page.