React Media Queries

1.10.0 · active · verified Tue Apr 21

react-media is a React component that enables declarative CSS media queries directly within React applications, simplifying responsive design. As of version 1.10.0, it offers a stable and widely used API for conditionally rendering components based on various viewport characteristics. While its release cadence is moderate rather than rapid, it has consistently received updates addressing compatibility with newer React versions and introducing key features like enhanced Server-Side Rendering (SSR) support via the `defaultMatches` prop and improved iframe integration with the `targetWindow` prop. It distinguishes itself by providing a clean, component-based abstraction over the native `window.matchMedia` API, allowing developers to focus on component logic rather than direct DOM API interaction.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the <Media> component to render different content based on predefined CSS media queries, including handling print media.

import React from 'react';
import { Media } from 'react-media';

interface MyResponsiveComponentProps {
  children: React.ReactNode;
}

const MyResponsiveComponent: React.FC<MyResponsiveComponentProps> = ({ children }) => {
  return (
    <Media queries={{
      small: '(max-width: 599px)',
      medium: '(min-width: 600px) and (max-width: 1199px)',
      large: '(min-width: 1200px)',
      print: 'print'
    }}>
      {matches => (
        <div style={{ padding: '20px', border: '1px solid #ccc' }}>
          {matches.small && <p>You are on a small screen or mobile device.</p>}
          {matches.medium && <p>You are on a tablet or medium-sized screen.</p>}
          {matches.large && <p>You are on a desktop or large screen.</p>}
          {matches.print && <p>Preparing for print!</p>}
          {!matches.small && !matches.medium && !matches.large && !matches.print && (
            <p>No specific media query matched (perhaps a server-side render without defaultMatches).</p>
          )}
          {children}
        </div>
      )}
    </Media>
  );
};

export default MyResponsiveComponent;

view raw JSON →