WIP
Keep the browser viewport sync with your redux state.
First of all, if you want to do reponsive things with React and Redux, take a look at redux-responsive.
redux-viewport is designed to dynamically set viewport listeners in your application.
examples :
- responsive breakpoints are not the same between pages.
- responsive breakpoints are sent by the server.
- disable some responsive breakpoints in specific situation.
npm install --save guillaumearm/redux-viewport
import { createStore, applyMiddleware } from 'redux';
import { viewportMiddleware, viewportReducer } from 'redux-viewport';
import * as reducers from './reducers';
const rootReducer = {
...reducers,
viewport: viewportReducer, // this is a reducer, so you can put it everywhere you want in the state
};
const initialState = {};
const store = createStore(rootReducer, initialState, applyMiddleware(viewportMiddleware));
import { listenMedia } from 'redux-viewport';
const { dispatch, getState } = store;
const getIsLandScape = () => getState().viewport.isLandscape;
getIsLandScape() // undefined
dispatch(listenMedia('isLandscape', '(orientation: landscape)'));
getIsLandScape() // true/false
state.viewport.isLandscape
will be keep in sync with the browser.
- you can use clearMedia() action creator to stop listening media.
import { clearMedia } from 'redux-viewport';
dispatch(clearMedia('isLandscape'))
getIsLandScape() // undefined
- if you want to keep last boolean value in the store when clear a media, use the optional parameter of clearMedia()
import { clearMedia } from 'redux-viewport';
dispatch(clearMedia('isLandscape'), { keepValue: true });
getIsLandScape() // true/false
import { listenMedia } from 'redux-viewport';
dispatch(listenMedia({
'isLandscape': '(orientation: landscape)',
'isPortrait': '(orientation: portrait)',
}))
import { clearMedia } from 'redux-viewport';
dipatch(clearMedia([
'isLandscape,'
'isPortrait',
]))
note you can use keepValue
option here too.
redux-viewport actions are FSA compliant :
@@viewport/LISTEN_MEDIA
is created by listenMedia()
import { listenMedia, LISTEN_MEDIA } from 'redux-viewport';
listenMedia('isLandscape', '(orientation: landscape)');
/* return this action
{
type: LISTEN_MEDIA, // @@viewport/LISTEN_MEDIA
payload: {
'isLandscape': '(orientation: landscape)',
},
}
*/
@@viewport/CLEAR_MEDIA
is created by clearMedia()
import { clearMedia, CLEAR_MEDIA } from 'redux-viewport';
clearMedia('isLandscape');
/* return this action
{
type: CLEAR_MEDIA, // @@viewport/CLEAR_MEDIA
payload: ['isLandscape'],
meta: { keepValue: false },
}
*/
@@viewport/UPDATE_MEDIA
is dispatched by the viewport middleware, you can catch them in your reducers.
import { UPDATE_MEDIA } from 'redux-viewport';
/*
{
type: UPDATE_MEDIA, // @@viewport/UPDATE_MEDIA
payload: {
'isLandscape': true,
},
}
*/
Feel free to contribute. please see CONTRIBUTING.MD