Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to check screen width in ReactJS

Getting Started

Imagine you're building a website for a bakery. You have all the recipes, photos, and content you need. But, you face a challenge: your website looks great on a laptop, but on a mobile phone, your bakery's delicious cupcakes shrink into unappetizing, tiny blobs. That's where responsive design comes into play.

Responsive Design: The Bakery Analogy

Let's continue with our bakery analogy. Responsive design is like having a flexible recipe. If you have fewer guests, you can adjust the recipe to make fewer cupcakes. If you have more guests, you can increase the ingredients proportionally for a larger batch. Similarly, in web development, we need to adjust our website's design based on the screen size, or "guests," in this case.

Meet ReactJS: Your Bakery Assistant

ReactJS is a powerful tool or "bakery assistant" that helps you manage the complexity of your website (the bakery). However, ReactJS doesn't provide a built-in method to detect screen width. To overcome this, we'll use a combination of JavaScript's window object and ReactJS's state.

JavaScript's Window Object: The Measuring Tape

JavaScript's window object is like a measuring tape. It provides properties and methods that allow you to interact with the browser window. One of these properties is window.innerWidth, which gives the width of the window's content area in pixels.

Here's a simple example:

console.log(window.innerWidth);

When you run this code, it prints the width of your window's content area to the console.

ReactJS's State: The Recipe Card

In our bakery, the recipe card holds the current state of our recipe. Similarly, in ReactJS, we use state to hold component's data that may change over time. We can use the useState hook in ReactJS to store our screen width.

Here's how we can set up a state for our screen width:

import React, { useState } from 'react';

function MyComponent() {
  const [width, setWidth] = useState(window.innerWidth);

  //...
}

In this code, we're calling the useState function with the initial value of window.innerWidth. This returns an array with two elements: the current state (width) and a function to update it (setWidth).

Detecting Screen Width Changes: The Oven Timer

Baking cupcakes requires checking the oven frequently to prevent them from overcooking. Similarly, we need to continuously check for changes in our screen width.

JavaScript provides us with the resize event, which is fired every time the document view (window) has been resized.

We can listen for this event using window.addEventListener. When the resize event is fired, we can update our state with the new window width.

Here's how we can do it:

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => {
      setWidth(window.innerWidth);
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  //...
}

In this code, we're using the useEffect hook, which lets you perform side effects in function components. In our case, the side effect is listening for the resize event and updating our state.

We define a function handleResize that updates our width state, then we add it as an event listener to the resize event.

The return statement in the useEffect hook serves as a cleanup function. Just like turning off the oven and putting away the baking ingredients after baking cupcakes, it's important to clean up after ourselves. Here, we remove the event listener when the component unmounts or re-renders.

Conclusion: Enjoy Your Responsive Cupcakes

Congratulations! Now, you're not only a baker but also a ReactJS developer who can adjust your website's design based on the user's screen size. You have learned how to use JavaScript's window object to measure the screen width, and ReactJS's state to store it.

Remember, baking (and coding) is as much about the process as it is about the end product. So, keep experimenting with different ingredients (coding techniques) and don't be afraid to make mistakes. Happy baking and coding!