Skip to content

A react component to render different content on mobile and desktop. Uses window.matchMedia API.

Notifications You must be signed in to change notification settings

damusnet/react-device-switch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

react-device-switch

A react component to render different content on mobile and desktop


Build Status Code Coverage downloads version MIT License

size gzip size module formats: umd, cjs, and es

Watch on GitHub Star on GitHub Tweet

The problem

Split your components by device target and do responsive JavaScript!

This solution

A tiny react library, with no dependencies, that accepts a single breakpoint and uses window.matchMedia.

device-switch

Installation

This module is distributed via npm, which is bundled with node, and should be installed as one of your project's dependencies:

npm install --save react-device-switch

This package also depends on react and prop-types. Please make sure you have those installed as well.

Usage

See the complete example.

react-device-switch uses the react Context API. You need to import the <DeviceSizeListener /> provider at the top level of your app, and the <DeviceSwitch /> consumer wherever you want to render content specific to a device size.

import React from "react";

import { DeviceSizeListener, DeviceSwitch } from "react-device-switch";

const BREAKPOINT = "min-width: 600px";

const App = () => (
  <DeviceSizeListener breakpoint={BREAKPOINT}>
    <DeviceSwitch mobileRender="Mobile!" desktopRender="Not a Mobile!" />
  </DeviceSizeListener>
);

export default App;

Alternatively, you can use <DeviceMobile /> and <DeviceDesktop />:

import React from "react";

import {
  DeviceSizeListener,
  DeviceMobile,
  DeviceDesktop
} from "react-device-switch";

const BREAKPOINT = "min-width: 600px";

const App = () => (
  <DeviceSizeListener breakpoint={BREAKPOINT}>
    <DeviceMobile>Mobile!</DeviceMobile>
    <DeviceDesktop>Not a Mobile!</DeviceDesktop>
  </DeviceSizeListener>
);

export default App;

Other Solutions

LICENSE

MIT

About

A react component to render different content on mobile and desktop. Uses window.matchMedia API.

Resources

Stars

Watchers

Forks

Packages

No packages published