React + TypeScript: Re-render a Component on Window Resize

Last updated on September 17, 2021 A Goodman Loading... Post a comment

This article shows you how to re-render a React component when the window (the document view) gets resized. We’ll cover the basics and then build a complete example with modern things like hooks, functional components, and TypeScript.

Overview

Currently, React doesn’t support an event named onResize or anything like so. However, we can use the window.resize event that is supported natively by web browsers. This event fires when the window has been resized.

You can set up the event handler function in one of two ways below:

window.resize = myHandlerFunction;

Or:

window.addEventListener('resize', myHandlerFunction);

Implement with the useEffect hook:

 useEffect(() => {
    window.onresize = myHandlerFunction;

    // You can also use:
    // window.addEventListener('resize', myHandlerFunction);
  }, []);

To re-render one component (or many components) when the user resizes the window, we can use the useState hook. For more clarity and get a practical sense, see the end-to-end example below.

The Example

App Preview

The React app we are going to build displays the width and height of the window. When the width is less than or equal to 500px, the background will be white. When the width is from 501px to 700px, the background will be green. Otherwise, the background is orange.

Here’s how it works:

The Code

1. Create a new React TypeScript project:

npx create-react-app kindacode_example --template typescript

The name doesn’t matter. Choose whatever you like.

2. Full source code in src/App.tsx with explanations:

// App.tsx
// Kindacode.com
import React, { useState, useEffect, FunctionComponent } from "react";

// Create an interface for the size of the window
interface Size {
  width: number;
  height: number;
}

const App: FunctionComponent = () => {
  // The size of the window
  const [size, setSize] = useState<Size>();

  // This function updates the state thus re-render components
  const resizeHanlder = () => {
    const width = window.innerWidth;
    const height = window.innerHeight;

    setSize({
      width: width,
      height: height,
    });
  };

  // Listening for the window resize event
  useEffect(() => {
    window.onresize = resizeHanlder;

    // You can also use:
    // window.addEventListener('resize', resizeHanlder);
  }, []);

  return (
    <div
      // Change the backgronund color according to the window's width
      style={{
        ...styles.container,
        backgroundColor:
          !size || size.width <= 500
            ? "white"
            : size && size.width <= 700
            ? "green"
            : "orange",
      }}
    >
      {/* Display width and height as text */}
      {size && (
        <>
          <h2>Width: {size.width}</h2>
          <h2>Height: {size.height}</h2>
        </>
      )}

      {!size && <h2>Use your mouse to resize the window</h2>}
      <h5>Welcome to KindaCode.com</h5>
    </div>
  );
};

// Style the container
const styles = {
  container: {
    width: "100vw",
    height: "100vh",
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
  },
} as const;

export default App;

3. Run the project and head to http://localhost:3000 to check the result:

npm start

Conclusion

You’ve learned how to update components on window resize. If you’d like to learn more new and interesting things of React, take a look at the following articles:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles