EN
React - rerender component on browser resize
0
points
In this article, we would like to show you how to rerender component on browser resize in React.
In the example below, we use the useState
and useEffect
hooks. We store the current window dimensions in the component state.
Run the example below and resize the window to see the result.
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from "react";
// import ReactDOM from "react-dom";
const App = () => {
const [dimensions, setDimensions] = React.useState({
height: window.innerHeight,
width: window.innerWidth
})
const handleResize = () => {
setDimensions({
height: window.innerHeight,
width: window.innerWidth
});
}
React.useEffect(() => {
window.addEventListener('resize', handleResize)
return () => { window.removeEventListener('resize', handleResize) }
});
return (
<div>
<p>Window height: {dimensions.height} </p>
<p>Window width: {dimensions.width} </p>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
Now let's follow this code step by step:
dimensions
state initialization - an object with the current window height and width assigned.- Component rendering.
- When the window size changes,
addEventListener
catches it and calls thehandleResize
method. handleResize
method usingsetDimensions
changes the stored window dimensions to the current one.- The component re-renders.