Home  >  Article  >  Web Front-end  >  How to Rerender View in React When Browser Window Resizes?

How to Rerender View in React When Browser Window Resizes?

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 19:38:291062browse

How to Rerender View in React When Browser Window Resizes?

Rerendering View on Browser Resize with React

In React, it's possible to automatically update the view when the browser window is resized, providing a responsive user experience.

Window Resize Detection

Adding jQuery's window resize listener is a straightforward approach to detect window resizing. However, React offers some more React-specific methods:

React Hooks

React Hooks provide a declarative way to add window resize handling. The useWindowSize Hook can be defined as follows:

<code class="javascript">import React, { useLayoutEffect, useState } from 'react';

function useWindowSize() {
  const [size, setSize] = useState([0, 0]);
  useLayoutEffect(() => {
    const updateSize = () => setSize([window.innerWidth, window.innerHeight]);
    window.addEventListener('resize', updateSize);
    updateSize();
    return () => window.removeEventListener('resize', updateSize);
  }, []);
  return size;
}</code>

React Class Components

For class components, the lifecycle method componentDidMount can be used to start listening to window resize events. The following code demonstrates this:

<code class="javascript">import React from 'react';

class ShowWindowDimensions extends React.Component {
  state = { width: 0, height: 0 };

  updateDimensions = () => {
    this.setState({ width: window.innerWidth, height: window.innerHeight });
  };

  componentDidMount() {
    window.addEventListener('resize', this.updateDimensions);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.updateDimensions);
  }

  render() {
    return <span>Window size: {this.state.width} x {this.state.height}</span>;
  }
}</code>

By incorporating window resize detection into your React application, you can ensure that your UI remains responsive and adapts seamlessly to different screen sizes.

The above is the detailed content of How to Rerender View in React When Browser Window Resizes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn