Home >Web Front-end >JS Tutorial >How to Re-render React View on Browser Resize: jQuery vs React-Centric Approach?
Re-rendering the View on Browser Resize with React
In the given React application, the goal is to re-render the view when the browser window is resized. This enables the dynamic adjustment of UI elements, such as the positioning of blocks in a Pinterest-like layout.
Using Window Resize Library:
One common approach is to use jQuery's window resize event, as suggested in the question. By adding the following code, you can re-render the component whenever the window is resized:
$( window ).resize(function() { // Re-render the component });
React-Centric Approach:
However, there is a more "React" approach to achieving this using the useEffect Hook. This Hook allows you to perform side effects in a component, such as listening to window events. To use useEffect for window resize, you can define a custom Hook like this:
import React, { useState, useEffect } from 'react'; function useWindowSize() { const [size, setSize] = useState([0, 0]); useEffect(() => { function updateSize() { setSize([window.innerWidth, window.innerHeight]); } window.addEventListener('resize', updateSize); updateSize(); return () => window.removeEventListener('resize', updateSize); }, []); return size; }
You can then use this Hook in your component to access the window size and trigger a re-render whenever it changes:
import React, { useState, useEffect } from 'react'; import { useWindowSize } from './useWindowSize'; function MyApp() { // ... const [windowSize, setWindowSize] = useWindowSize(); useEffect(() => { // Re-render the component when the window size changes setWindowSize(useWindowSize()); }, [windowSize]); return ( // ... ); }
This approach is more encapsulated and follows React's lifecycle patterns, keeping your component's code clean and maintainable.
The above is the detailed content of How to Re-render React View on Browser Resize: jQuery vs React-Centric Approach?. For more information, please follow other related articles on the PHP Chinese website!