Skip to content

Instantly share code, notes, and snippets.



Last active Jan 17, 2017
What would you like to do?
React + Redux Contrived Primer
// Destructure the Provider component and connect method from the
// react-redux module. The component wraps your React application in
// the code necessary to work properly with state and prop updates
// from Redux. The connect method allows you to connect individual
// React components to Redux for Redux store to prop mapping.
import { Provider, connect } from 'react-redux'
// Destructure the createStore method from the core redux module
// This method allows you to create your global store to house all your
// state values and your reducers to update state values
import { createStore } from 'redux'
import ReactDOM from 'react-dom'
var reducer = function(previousState, action){
// Replicate the state object, don't mutate it directly
let state = Object.assign({}, previousState)
// Only modify the state based on the action.type is one we're looking for
case "toggleButton":
state.buttonIsOn =
return state
// Create a globally accessible Redux store so we can call
// store.dispatch() anywhere, not just connected React Components = createStore(reducer)
// Build a React Component like normal
class MyApplicationComponent extends React.Component {
constructor(props) {
// Bind the Component as "this" when calling this.handleButtonClick
// You only need to do this here to avoid having to do it inline in your
// JSX code. This is done this way in the example to highlight its
// necessity so we can still access this.props within this.handleButtonClick()
this.handleButtonClick = this.handleButtonClick.bind(this)
// Handle the click of the button
handleButtonClick() {
// When you have "connected" a component to Redux you automatically
// get the dispatch() method as a props method. This is why we must
// bind(this) in the constructor() since the handleButtonClick method
// is called in a context where the DOM element would normally be "this"
type: "toggleButton",
// This is boolean, so just send the inverse of what it is currently to toggle
data: !this.props.buttonIsOn
render() {
return (
<h1>My contrived example</h1>
<p>The button is: {this.props.buttonIsOn ? "on" : "off"}</p>
<button onClick={this.handleButtonClick}>Toggle</button>
// Map Redux store values to properties using Redux's connect method
// Normally, this would be the export value of a module and wouldn't
// require the MyApplicationComponent => MyApplication conversion
var MyApplication = connect(function(state, localProps) {
// Return an Object that will server as the Component's this.props
return {
buttonIsOn: state.buttonIsOn
// Finally, wrap our React application in a Redux store provider and render like normal
<Provider store={store}>
<MyApplication />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment