• Stars
    star
    427
  • Rank 98,373 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 5 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐ŸŽ‰ React library to render components only on specific viewports ๐Ÿ”ฅ

React Socks

Build Status npm version dependencies Status License: MIT

Wrap your components with React Socks to prevent unnecessary render in different viewports.

<Breakpoint small down>
  <MyAwesomeMobileMenu>
    This component will render only in mobile devices
  </MyAwesomeMobileMenu>
</Breakpoint>

Why? start with why

Conventionally we have been writing css media queries for different viewports to hide and show elements that are always present in the DOM. With React taking over the world, everything is about rendering components into the DOM. React Socks helps you conditionally render elements based on viewports.

  1. Render viewport specific components without hassle

  2. You can define your own breakpoints (Eg. xs, ipad, bigmonitors) and use them

  3. You can improve your app performance if you lazy load your viewport specific components

  4. Simpler and sweeter syntax for ease of use

Install

$ npm install --save react-socks

Usage

Just wrap your top level component with BreakpointProvider and use the Breakpoint component anywhere you need.

Note: BreakpointProvider was introduced only in v1.0.0. It's not available in previous alpha versions.

import  { Breakpoint, BreakpointProvider } from 'react-socks';

// entry file (usually App.js or index.js)
const App = () => (
  <BreakpointProvider>
    <Example />
  </BreakpointProvider>
);
// Example.js
const Example = () => {
  return (
    <div>
      <Breakpoint small down>
        <div>I will render only in mobile devices</div>
      </Breakpoint>

      <Breakpoint medium only>
        <div>I will render only in tablets (iPad, etc...)</div>
      </Breakpoint>

      <Breakpoint medium down>
        <div>I will render in tablets (iPad, etc...) and everything below (mobile devices)</div>
      </Breakpoint>

      <Breakpoint medium up>
        <div>I will render in tablets (iPad, etc...) and everything above (laptops, desktops)</div>
      </Breakpoint>

      <Breakpoint large up>
        <div>I will render in laptops, desktops and everything above</div>
      </Breakpoint>

      {/* Add breakpoints on the fly using custom queries */}

      <Breakpoint customQuery="(min-width: 500px)">
        <div style={{backgroundColor: 'red' }}>
          Custom breakpoint: (min-width : 500px)
        </div>
      </Breakpoint>
      
      <Breakpoint customQuery="(max-width: 1000px)">
        <div style={{backgroundColor: 'yellow' }}>
          Custom breakpoint: (max-width : 1000px)
        </div>
      </Breakpoint>
      
      <Breakpoint customQuery="(min-width: 500px) and (max-width: 700px)">
        <div style={{backgroundColor: 'lightblue' }}>
          Custom breakpoint: (min-width : 500px) && (max-width : 700px)
        </div>
      </Breakpoint>
    </div>
  );
};

API

Set Default Breakpoints

You can define your own breakpoints.

  • Pass an array of objects with the breakpoint name and width in px to setDefaultBreakpoints once in your App.js or your React entry file.

Note: You only need to set default breakpoints once in your app

import { setDefaultBreakpoints } from 'react-socks';

setDefaultBreakpoints([
  { xs: 0 },
  { s: 376 },
  { m: 426 },
  { l: 769 },
  { xl: 1025 }
]);

<Breakpoint m only>
    I will render only in m devices
</Breakpoint>
  • You can use any breakpoint name (Eg. cats, puppies, dinosaurs, etc) and width.
setDefaultBreakpoints([
  { cats: 0 },
  { dinosaurs: 900 }
]);

<Breakpoint cats only>
    Only cats can render me
</Breakpoint>
  • If you don't set a default breakpoint, the library will fallback to Bootstrap 4 default breakpoints as described below.
setDefaultBreakpoints([
  { xsmall: 0 }, // all mobile devices
  { small: 576 }, // mobile devices (not sure which one's this big)
  { medium: 768 }, // ipad, ipad pro, ipad mini, etc
  { large: 992 }, // smaller laptops
  { xlarge: 1200 } // laptops and desktops
]);

Set Default Width

You can define your own default width. This will help when you want to render a particular default width from the server. Usually in the server, there are no breakpoints and the lib defaults to 0 and renders mobile views. Use this API to change that.

  • Pass width in px to setDefaultWidth once in your App.js or your React entry file.

Note: You only need to set default width once in your app

import { setDefaultWidth } from 'react-socks';

setDefaultWidth(992); // render desktop components in the server

Breakpoint

Import the Breakpoint component anywhere in the your code and start using it with your breakpoint and modifier props.

// small is breakpoint
// down is modifier
<Breakpoint small down>
  <MyAwesomeMobileMenu>
    This component will render only in mobile devices
  </MyAwesomeMobileMenu>
</Breakpoint>

You have three modifiers

  • only - will render the component only in the specified breakpoint.

  • up - will render the component in the specified breakpoint and all the breakpoints above it (greater than the width).

  • down - will render the component in the specified breakpoint and all the breakpoints below it (less than the width).

Custom Breakpoints ๐Ÿ†•

Now, you can add a breakpoint of any width by using this prop: customQuery. Simply write your media query as a string and pass it to customQuery

  <Breakpoint customQuery="(min-width: 500px)">
    <div style={{backgroundColor: 'red' }}>
      Custom breakpoint: (min-width : 500px)
    </div>
  </Breakpoint>
  
  <Breakpoint customQuery="(max-width: 1000px)">
    <div style={{backgroundColor: 'yellow' }}>
      Custom breakpoint: (max-width : 1000px)
    </div>
  </Breakpoint>
  
  <Breakpoint customQuery="(min-width: 500px) and (max-width: 700px)">
    <div style={{backgroundColor: 'lightblue' }}>
      Custom breakpoint: (min-width : 500px) && (max-width : 700px)
    </div>
  </Breakpoint>

Note: customQuery will be ignored if you have mentioned any modifiers like up, down & only

Use customQuery only if you want to make use of arbitary breakpoints.

Use Current Width / Breakpoint Name

If you call useCurrentWidth in the render function, you can access the current width directly:

import { useCurrentWidth } from 'react-socks'

const CustomComponent = () => {
  const width = useCurrentWidth()
  if (width < 500) {
    return <h1>Hello!</h1>
  } else {
    return <h2>Hello!</h2>
  }
}

You can also use the current breakpoint name with useCurrentBreakpointName:

import { useCurrentBreakpointName } from 'react-socks'

const CustomComponent = () => {
  const breakpoint = useCurrentBreakpointName()
  if (breakpoint == 'small') {
    return <h1>Hello!</h1>
  } else {
    return <h2>Hello!</h2>
  }
}

Contributors

Thanks goes to these amazing people ๐ŸŽ‰


Dinesh Pandiyan


Capelo


Adarsh


Patryk


WRNGFRNK


Farhad Yasir


Entkenntnis


Douglas Moore


Abdul rehman


Nawaz Khan


hems.io

License

MIT ยฉ Dinesh Pandiyan

More Repositories

1

dev-landing-page

Minimal landing page for developers
HTML
1,220
star
2

react-redux-boilerplate

A minimal React-Redux boilerplate with all the best practices
JavaScript
780
star
3

npm-module-boilerplate

Boilerplate for npm modules with ES6 features and all the best practices
JavaScript
387
star
4

blogster

A collection of beautiful, accessible and performant Astro blog templates.
Astro
310
star
5

typy

Minimal JavaScript type checking library
JavaScript
227
star
6

browser-or-node

Check where your code is running. In the browser or in node.js environment.
JavaScript
195
star
7

react-render-in-browser

React library to render browser specific content
JavaScript
159
star
8

cache-busting-example

JavaScript
101
star
9

tweet-fancy

๐Ÿš€ Tweet with bold, italics and strikethough text
CSS
42
star
10

design-system-boilerplate

A design system boilerplate monorepo with opinionated principles, theming and token setup to build your own design system.
TypeScript
40
star
11

gatsby-boilerplate

CSS
31
star
12

progressive-rendering-react

Example setup to progressively render a React app from the server
JavaScript
30
star
13

progressive-rendering

Demo โ€” Stream portions of a webpage as chunks from the server
HTML
27
star
14

testing-hooks

Code examples to test custom React hooks with Enzyme
JavaScript
24
star
15

react-npm-package-boilerplate

Boilerplate code for building a React NPM library
JavaScript
24
star
16

code-cheatsheet

Quick reference code snippets curated from various sources
TypeScript
19
star
17

axios-retry-interceptor

Configurable Axios Interceptor to retry failed http calls.
JavaScript
18
star
18

keystone-static-blog

Starter template to statically generate blog websites with Next.js and Keystone
TypeScript
13
star
19

apollo-graphql-playbook

Notes and guides on using apollo client's APIs
12
star
20

portfolio

JavaScript
9
star
21

react-monorepo

Monorepo starter template to build React applications
TypeScript
9
star
22

babel-plugin-render-logger

โš™๏ธ Babel plugin that automatically adds a console statement to React components and makes debugging easier
JavaScript
7
star
23

all-my-writeups

Curation of all my writeups ๐ŸŽ‰
6
star
24

fahid-jokes

https://fahidjokes.netlify.com ๐Ÿ˜‚
JavaScript
5
star
25

git-handbook

Handbook on how to use git commands and strategies that make life easier
4
star
26

keystone-in-next

Moved to https://github.com/keystonejs/keystone/tree/main/examples/nextjs-keystone
TypeScript
3
star
27

happy-birthday-bhat

Bhat turns 25 - http://happybirthdaybhat.dkbox.in โšก๏ธ
CSS
3
star
28

dineshpandiyan.com

Astro
3
star
29

keystone-docker

TypeScript
3
star
30

next-batch

A promise batching utility mostly used in GraphQL resolvers to avoid N + 1 data fetching
TypeScript
2
star
31

awesome-saas-stack

A curation of SaaS tools to build modern web applications.
2
star
32

node-express-boilerplate

JavaScript
2
star
33

cloudflare-pothos-boilerplate

Boilerplate to get started with Pothos in Cloudflare workers
TypeScript
2
star
34

keystone-template

Starter template to kickstart a Keystone project
TypeScript
1
star
35

next-multi-zone

1
star
36

v1.dineshpandiyan.com

v1 of dineshpandiyan.com
CSS
1
star
37

index

๐Ÿ‘‹ Repos grouped together for quicker navigation.
1
star
38

outstatic-example

CSS
1
star
39

del-key

Delete keys from deeply nested objects in JavaScript
JavaScript
1
star
40

scrabble-game

Command line based scrabble game with in-built dictionary and alphabet scores
Java
1
star
41

parcel-react-starter

Starter template to build React applications. Tailwind + TypeScript.
TypeScript
1
star
42

react-ssr-parcel

This repo is an example setup to server render a React app
JavaScript
1
star
43

hook-diary

๐Ÿš€ Open collection of custom react hooks
JavaScript
1
star
44

global-package-version

Library to check any npm module's version from browser console
JavaScript
1
star
45

v2.dineshpandiyan.com

v2 of dineshpandiyan.com
JavaScript
1
star
46

dontannoyme

Chrome Extension to block FB posts based on provided keywords
JavaScript
1
star
47

eventmanagement-front-end

JavaScript
1
star
48

v4.dineshpandiyan.com

v4 of dineshpandiyan.com
HTML
1
star
49

v3.dineshpandiyan.com

v3 of dineshpandiyan.com
HTML
1
star
50

parcel-extract-vendor-bundle

Example repo to extract vendors into a separate bundle using parcel shared bundles concept
TypeScript
1
star
51

spectacle-template-nextjs

A spectable template that doesn't work very well
TypeScript
1
star
52

yoga-pothos

Template to build a GraphQL API using graphql-yoga and pothos
TypeScript
1
star
53

git-rebase-vs-merge

Example repo to demonstrate how rebase vs merge works
JavaScript
1
star
54

react-devtools-demo

Demo project for React Devtools talk at React Sydney Sep 2019
JavaScript
1
star
55

parcel-react-package

React package template with parcel build setup
JavaScript
1
star
56

next13-edge-cache-bug

TypeScript
1
star
57

parcel-react-bare-minimum

Bare minimum parcel react web app boilerplate I use as a template to open issues in Parcel repo. TypeScript + Emotion
HTML
1
star