react-responsive

repository·master·Indexed 27 days ago

https://github.com/yocontra/react-responsive

A React module for implementing media queries to enable responsive design. It provides the useMediaQuery hook for functional components and the MediaQuery component for conditional rendering. The library supports custom device settings for SSR and testing via ResponsiveContext.Provider, an onChange callback for match changes, and a toQuery utility to convert feature objects into CSS media query strings.

Tokens
2.1K
Snippets
6
Records
16
Agent score
93%

What's inside react-responsive

  1. Provide device settings via Context for SSR and Testing

    master

    To provide device settings to all useMediaQuery hooks in a component tree (e.g., for SSR or unit testing), use ResponsiveContext.Provider from react-responsive.

    // Server-Side Rendering example
    import { Context as ResponsiveContext } from 'react-responsive'
    import { renderToString } from 'react-dom/server'
    import App from './App'
    
    const mobileApp = renderToString(
      <ResponsiveContext.Provider value={{ width: 500 }}>
        <App />
      </ResponsiveContext.Provider>
    )
    
    // Testing example
    import { Context as ResponsiveContext } from 'react-responsive'
    import { render } from '@testing-library/react'
    import ProductsListing from './ProductsListing'
    
    test('matches the snapshot', () => {
      const { container: mobile } = render(
        <ResponsiveContext.Provider value={{ width: 300 }}>
          <ProductsListing />
        </ResponsiveContext.Provider>
      )
      // ... assertions
    })
  2. Disable SSR for react-responsive in Next.js

    master

    If using Next.js, you can disable server-side rendering for components using react-responsive by using next/dynamic with ssr: false.

    import dynamic from 'next/dynamic'
    const MediaQuery = dynamic(() => import('react-responsive'), { 
      ssr: false 
    })
  3. Force device settings with the `device` prop

    master

    You can override automatically detected device settings by passing a device object as the second argument to useMediaQuery. This is useful for Server-Side Rendering (SSR) or testing. The device property always takes precedence over detected settings.

    import { useMediaQuery } from 'react-responsive'
    
    const Example = () => {
      const isDesktopOrLaptop = useMediaQuery(
        { minDeviceWidth: 1224 },
        { deviceWidth: 1600 } // `device` prop overrides detection
      )
    
      return (
        <div>
          {isDesktopOrLaptop && <p>This renders because deviceWidth was overridden to 1600.</p>}
        </div>
      )
    }
  4. Use the useMediaQuery hook

    master

    The useMediaQuery hook (available since v8.0.0) allows you to detect media query matches within a functional component. You can pass a full CSS query string via the query property, or use camel-cased shorthands like minWidth, maxWidth, orientation, and minResolution. Numbers provided as shorthands are automatically converted to px.

    import React from 'react'
    import { useMediaQuery } from 'react-responsive'
    
    const Example = () => {
      const isDesktopOrLaptop = useMediaQuery({ minWidth: 1224 })
      const isBigScreen = useMediaQuery({ minWidth: 1824 })
      const isTabletOrMobile = useMediaQuery({ maxWidth: 1224 })
      const isPortrait = useMediaQuery({ orientation: 'portrait' })
      const isRetina = useMediaQuery({ minResolution: '2dppx' })
    
      return (
        <div>
          {isDesktopOrLaptop && <p>You are a desktop or laptop</p>}
          {isBigScreen && <p>You have a huge screen</p>}
          {isTabletOrMobile && <p>You are a tablet or mobile phone</p>}
          <p>Your are in {isPortrait ? 'portrait' : 'landscape'} orientation</p>
          {isRetina && <p>You are retina</p>}
        </div>
      )
    }
  5. Use the MediaQuery component

    master

    The MediaQuery component can be used to conditionally render children based on media query matches. It supports two usage patterns:

    1. As a wrapper: Children are rendered only if the media query matches.
    2. As a render prop: A function is passed as a child, receiving matches (boolean) as an argument.
    import MediaQuery from 'react-responsive'
    
    const Example = () => (
      <div>
        <h1>Device Test!</h1>
        <MediaQuery minWidth={1224}>
          <p>You are a desktop or laptop</p>
          <MediaQuery minWidth={1824}>
            <p>You also have a huge screen</p>
          </MediaQuery>
        </MediaQuery>
        <MediaQuery minResolution="2dppx">
          {(matches) =>
            matches ? <p>You are retina</p> : <p>You are not retina</p>
          }
        </MediaQuery>
      </div>
    )
  6. Reference: Device property keys and types

    master

    When using the device prop to override settings, you can use the following keys:

    Keys:

    • orientation
    • scan
    • aspectRatio
    • deviceAspectRatio
    • height
    • deviceHeight
    • width
    • deviceWidth
    • color
    • colorIndex
    • monochrome
    • resolution
    • type

    type values: all, grid, aural, braille, handheld, print, projection, screen, tty, tv, or embossed.

  7. Import MediaQuery type definitions

    master

    The library exports several types for defining media queries and features:

    • MediaQueryTypes: The set of available media query types.
    • MediaQueryType: A specific media query type.
    • MediaQueryFeatures: An object representing CSS media features (e.g., minWidth, orientation).
    • MediaQueryMatchers: Types used for matching queries.
    • MediaQueryAllQueryable: A type for objects that can be queried.