Last active
April 18, 2017 00:49
-
-
Save casesandberg/9de0682b1e451c71da4fa1b7cf8a593f to your computer and use it in GitHub Desktop.
Simplify Redux in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { simpleReducer, withReducer } from 'new-package' | |
export const INIT = 'TABS/INIT' | |
export const SELECT = 'TABS/SELECT' | |
// Where the reducer will be in the store | |
export const path = 'components.tabs' | |
// Simple Reducer that acts just like a switch on action.type | |
export const reducer = (state, action) => simpleReducer({ | |
[INIT]: { ...state, [action.id]: action.index }, | |
[SELECT]: { ...state, [action.id]: action.index }, | |
}) | |
export const actions = { | |
init: ({ id, index }) => ({ type: INIT, id, index }), | |
select: ({ id, index }) => ({ type: SELECT, id, index }), | |
} | |
// withReducer scopes down incoming state to match reducer | |
// it also provides guards if the data isnt at the specified path | |
export const selectors = withReducer(path, { | |
getActiveIndexById: (state, id) => state[id] | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { connect } from 'react-redux' | |
import { store } from 'new-package' | |
import { reducer, path, actions, selectors } from './actions' | |
const Tabs ({ activeIndex, select }) => { | |
// Only register the reducer when tabs is used | |
store.register(path, reducer) | |
return ( | |
<div> | |
Active Tab Index: { activeIndex } | |
<div onClick={ select } /> | |
</div> | |
) | |
} | |
export default connect( | |
(state, ownProps) => ({ | |
activeIndex: selectors.getActiveIndexById(state, ownProps.name) | |
}), | |
actions | |
)(Tabs) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import ReactDOM from 'react-dom' | |
import App from './App' | |
import { ProvideStore } from 'new-package' | |
ReactDOM.render( | |
// No need to provide a store, it bootstraps its own. | |
<ProvideStore> | |
<App /> | |
</ProvideStore>, | |
document.getElementById('root'), | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment