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

How to Rerender View in React When Browser Window Resizes?

Barbara Streisand
Release: 2024-10-19 19:38:29
Original
1096 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template