This is a small package to store the browser window's width and height in state.
Install:
npm install --save redux-window
Add the reduxWindow reducer:
import { combineReducers } from 'redux';
import reduxWindow from 'redux-window';
const reducers = combineReducers({
reduxWindow,
...other reducers
});
Then in index.js
, import resizeEvent and pass it your store:
import { resizeEvent } from 'redux-window';
import store from './store';
resizeEvent(store);
The resize event is throttled to allow dispatch to be fired a maximum of once every 200ms. To change the default wait time, pass a second parameter to resizeEvent.
resizeEvent(store, 500);
You can optionally pass this value in with an object too:
resizeEvent(store, { wait: 500 });
When the store is initialised on the server there is no access to the window object. Because of this you can set a default width and height for the initial render and the client will correct these values once it loads.
resizeEvent(store, {
wait: 500,
defaultWidth: 1200,
defaultHeight: 900,
});
To get the window width and height from state:
import { getWidth, getHeight } from 'redux-window';
function mapStateToProps(state, ownProps) {
return {
width: getWidth(state),
height: getHeight(state),
};
}
NOTE: the selectors require your reducer to use the key reduxWindow
, as in the example above.