Using Window.matchMedia in React

Using Window.matchMedia in React

Spoiler: Safari makes it messy

Why Use window.matchMedia?

Usually, we can use a css @media query to change how content is displayed for users with different screen sizes. Sometimes, however, it can be difficult to achieve your desired effect with CSS alone. Maybe:

  • the layout is so different that you might as well rewrite the entire component
  • you want to include some other logic, like different logging or something
  • your brain is fried, and you can’t figure out the CSS.

Whatever your reasoning, checking the screen size using JavaScript can be a useful tool.

Step 0: Set up

Let’s set the scene:

You have a React functional component, MyReponsiveComponent. You want to display one thing for desktop users and something completely different for users with narrower devices. You have a variable, isNarrowScreen, that you're using to switch between the two, but for now, it's always set to false.

const MyReponsiveComponent = () => {
  const isNarrowScreen = false;
  if (isNarrowScreen) {
    return (<div>This is what you see on mobile!</div>);
  } else {
    return (<div>This is what you see on desktop!</div>);

react reactjs

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

Why ReactJS?

React JS is the most popular JS library for building UI (User Interfaces), which is created by Facebook. We can build fast Single Page, modern Applications, or websites with React. So, the question here arises is why React is so important. Let's put some light on the features of react.

Share Code Between React Native and React JS

React provides support for the server-side and frontend. Today, React development services are in demand as more and more organizations are considering software solutions that are crafted from the framework.

Top ReactJS Development Company in USA - Hire React JS Developers

Hire ReactJS developers from a Top ReactJS Development Company in USA to developing User Interfaces on ReactJS framework.

Create React NAVBAR / MENU using React Router in ReactJS in Hindi in 2020

Welcome, how to create a react menu in Hindi. React js navbar in Hindi in 2020 using React Router Dom.