npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

redux-responsive-pistol-pete

v3.1.5

Published

Utilities for easily creating responsive designs in a redux architecture.

Downloads

2

Readme

redux-responsive

Build Status

A redux reducer for managing the responsive state of your application. Documentation is hosted here.

Why Use a Flux Store for Responsive Behavior?

redux-responsive does not require that you use React as your view library. However, since that is what is commonly used alongside redux, this documentation employs common React patterns.

There are many solutions for cleanly handling responsive designs in React applications. One common approach is to wrap a component in another component which is responsible for handling the behavior and passing the information down as a prop. While this at first seems good and the "react way", as the behavior gets more complicated, this quickly leads to a lot of boilerplate code in a single component. Also, depending on the implementation, it is possible that many copies of the responsive wrapper would create many different resize handlers.

Using a specialized store not only reduces the overall noise in a component, but also guarantees that only a single event listener is listening for resize.

Setup

First, add the reducer somewhere in your reducer tree. It's just a reducer so you can put it wherever you want! For example, you could put it in your top level call to combineReducers.

// reducer.js
import {combineReducers} from 'redux'
import {responsiveStateReducer} from 'redux-responsive'

export default combineReducers({
    browser: responsiveStateReducer,
})

Second, you must add the resize handlers to the window. To do this, use the provided store enhancer.

// store.js

import {createStore} from 'redux'
import {responsiveStoreEnhancer} from 'redux-responsive'
import reducer from './reducer'

const store = createStore(reducer, responsiveStoreEnhancer)

// or, if you have an initial state for the store
const store = createStore(reducer, initialState, responsiveStoreEnhancer)

export default store

Note that if you are also using some middlewares, the call will look more like this:

import {createStore, applyMiddlewares, compose} from 'redux'
import {responsiveStoreEnhancer} from 'redux-responsive'
import reducer from './reducer'

const store = createStore(
    reducer,
    compose(
        responsiveStoreEnhancer,
        applyMiddlewares(middleware1, middleware2)
    )
)

// or, if you have an initial state for the store
const store = createStore(
    reducer,
    initialState,
    compose(
        responsiveStoreEnhancer,
        applyMiddlewares(middleware1, middleware2)
    )
)

export default store

Now your store is ready to use. The store's default breakpoints match common device sizes and are accessible by the following names in your view:

const defaultBreakpoints = {
    extraSmall: 480,
    small: 768,
    medium: 992,
    large: 1200,
}

Using Custom Breakpoints

You can also create your own reducer based on custom breakpoints:

// reducer.js

import {combineReducers} from 'redux'
import {createResponsiveStateReducer} from 'redux-responsive'

export default combineReducers({
    browser: createResponsiveStateReducer({
        extraSmall: 500,
        small: 700,
        medium: 1000,
        large: 1280,
        extraLarge: 1400,
    }),
})

The Responsive State

The responsiveStateReducer (and the reducer returned by createResponsiveStateReducer) adds an object with the following keys to the store:

  • width: (number) The browser width. Note: With PerformanceMode enabled, this will take the value of the most recently matched breakpoint.
  • height: (number) The browser height. Note: With PerformanceMode enabled, this will take the value of the browser when the most recently matched breakpoint was satisfied.
  • mediaType: (string) The largest breakpoint category that the browser satisfies.
  • orientation: (string) The browser orientation. Has three possible values: "portrait", "landscape", or null.
  • lessThan: (object) An object of booleans that indicate whether the browser is currently less than a particular breakpoint.
  • greaterThan: (object) An object of booleans that indicate whether the browser is currently greater than a particular breakpoint.

For example, if you put the responsive state under the key browser (as is done in the examples above) then you can access the browser's width and current media type, and determine if the browser is wider than the medium breakpoint like so

// get the current state from the store
const state = store.getState()

// browser width (e.g. 1400)
state.browser.width
// browser height (e.g. 700)
state.browser.height
// browser media type (e.g. "large")
state.browser.mediaType
// browser orientation (takes a null value on desktops)
state.browser.orientation
// true if browser width is greater than the "medium" breakpoint
state.browser.greaterThan.medium

Example Usage

// MyComponent.js

import React from 'react'
import {connect} from 'react-redux'

// grab only the responsive state from the store
// (assuming you have put the `responsiveStateReducer` under
//  the key `browser` in your state tree)
function browserSelector({browser}) {
    return {browser}
}

@connect(browserSelector)
class MyComponent extends React.Component {
    render() {
        // grab the responsive state off of props
        const {browser} = this.props

        let message = `The viewport's current media type is: ${browser.mediaType}.`

        if (browser.lessThan.small) {
            message += 'Secret message for viewports smaller than than the "small" breakpoint!'
        } else if (browser.lessThan.medium) {
            message += 'Secret message for viewports between the "small" and "medium" breakpoints!'
        } else {
            message += 'Message for viewports greater than the "medium" breakpoint.'
        }

        return (
            <p>
                {message}
            </p>
        )
    }
}

Server-side Rendering

Isomorphic applications must make sure that the sever-rendered markup matches the DOM rendered by the client. Setting the calculateStateInitially option in the createResponsiveStoreEnhancer factory method to false tells the reducer to skip the initial responsive state calculation. The responsive state will contain the default values on both the server and the client side.

// store/configureStore.js

import {createStore} from 'redux'
import {createResponsiveStoreEnhancer} from 'redux-responsive'
import reducer from './reducer'

const store = createStore(
                    reducer,
                    createResponsiveStoreEnhancer({calculateStateInitially: false}))

export default store

The application should explicitly dispatch the action to recalculate the responsive state when the application is rendered by the client.

// client.js

// external imports
import ReactDOM from 'react-dom'
import {calculateResponsiveState} from 'redux-responsive'
// local imports
import store from 'path/to/store'

// render the application
ReactDOM.render(
    <Provider store={store}>
        // ...
    </Provider>,
    document.getElementById('app')
)

// calculate the initial state
store.dispatch(calculateResponsiveState(window))

Performance Mode

By default, the responsive state of your application is calculated every time the browser resizes. This incurs a very high overhead in large or very specialized apps. For those situations, redux-responsive provides a flag which limits the re-calculation of the responsive state to just when the state actually changes. When in performance mode, keep in mind that the reducer value for browser height and width are not continuously updating - they will only reflect the state of the browser when the media query actually changed.

// store/configureStore.js

import {createStore} from 'redux'
import {createResponsiveStoreEnhancer} from 'redux-responsive'
import reducer from './reducer'

const store = createStore(
                    reducer,
                    createResponsiveStoreEnhancer({performanceMode: true}))

export default store

Higher-Order Components

When building responsive applications in react, it's common to implement styles for each breakpoint and then apply them like so:

const commonStyle = {...}

const styles = {
    element: {
        ...commonStyle,
        color: 'blue',
    },
    elementThin: {
        ...commonStyle,
        color: 'black',
    }
}

// somewhere in your component...

<div style={browser.lessThan.medium ? styles.elementThin : styles.element} />

However this becomes very repetitive rather quickly. To help, redux-responsive provides a higher-order component for managing these styles. The follow is equivalent to the logic above:

import {StyleSheet} from 'redux-responsive/react'

const stylesheet = {
    element: {
        color: 'blue',
        _lessThan_medium: {
            color: 'black',
        }
    }
}

const component = StyleSheet(stylesheet)(({styles}) => (
    <div style={styles.element} />
))

Versioning

Semver is followed as closely as possible. For updates and migration instructions, see the changelog.