react-media-universal
react-media-universal
is a CSS media query component for React, for use with server side rendering.
It is based on react-media
and uses the same API, with the addition of a <MediaProvider>
component. It solves problems when hydrating a server side rendered app that uses <Media>
components for conditional rendering.
Installation
Using npm:
$ npm install --save react-media-universal
Then, use the <MediaProvider>
and <Media>
component as you would anything else:
// using ES modules; // using CommonJS modulesvar Media = ;var MediaProvider = MediaProvider;
The UMD build is also available on unpkg:
You can find the library on window.ReactMediaUniversal
.
Usage
Make sure to wrap your entire tree in the <MediaProvider>
component for the hydration from server side rendering to work properly.
For the API of the <Media>
component, see the docs for react-media
.
import React from "react";import Media MediaProvider from "react-media-universal"; Component { return <MediaProvider> <div> <Media ="(max-width: 599px)"> matches ? <p>The document is less than 600px wide</p> : <p>The document is at least 600px wide</p> </Media> </div> </MediaProvider> ; }
If you render a <Media>
component on the server, it always matches. To change this behaviour, use the defaultMatches
prop:
import React from "react";import Media MediaProvider from "react-media-universal"; Component { return <MediaProvider> <div> <Media ="(max-width: 599px)" = = /> </div> </MediaProvider> ; }
About
react-media-universal
is developed and maintained by Hyperlab. If you're intrested in this library, or the other things we do, please send us an e-mail!