ReactJS Middleware example

In this example below you will see how to do a ReactJS Middleware example with some HTML / CSS and Javascript

ReactJS middleware example using redux.This example displays a counter with +/- buttons, but as number 13 can attempt against the feelings of superstitious people, it will never appear on screen thanks to our middleware.

Thumbnail
This awesome code was written by -kaik-, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright -kaik- ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>ReactJS Middleware example</title>
  
  
  <link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css'>

      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div class="container"></div>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/redux/3.5.2/redux.js'></script>
<script src='https://wzrd.in/standalone/react-redux@4.2.1'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js'></script>
<script src='https://fb.me/react-dom-15.1.0.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/-kaik-/reactjs-middleware-example-vKEoNe */
.container {
  padding: 20px;
}

.form-inline input {
  display: inline-block;
  width: auto;
  margin: 5px;
}

.app div {
  margin: 50px 0px;
}

.counter-component button {
  margin: 0px 5px;
}


/*Downloaded from https://www.codeseek.co/-kaik-/reactjs-middleware-example-vKEoNe */
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/* kind of imports from codepen.io global vars */
var _Redux = Redux,
    createStore = _Redux.createStore,
    applyMiddleware = _Redux.applyMiddleware,
    combineReducers = _Redux.combineReducers;
var _reactRedux = reactRedux,
    Provider = _reactRedux.Provider,
    connect = _reactRedux.connect;

/*
 * ACTIONS
 */

var INCREASE_ACTION = 'INCREASE_ACTION';
var DECREASE_ACTION = 'DECREASE_ACTION';

/* increase action creator: payload = +1*/
var increaseActionCreator = function increaseActionCreator() {
  console.log("increased called");
  return {
    type: INCREASE_ACTION,
    payload: 1
  };
};

/* decrease action creator: payload = +-1*/
var decreaseActionCreator = function decreaseActionCreator() {
  return {
    type: DECREASE_ACTION,
    payload: -1
  };
};

/*
 * REDUCERS
 */

/* if INCREASE/DECREASE ACTION detected, modify state as defined in payload*/
var counterReducer = function counterReducer() {
  var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  var action = arguments[1];

  switch (action.type) {
    case INCREASE_ACTION:
    case DECREASE_ACTION:
      return state + action.payload;
  }

  return state;
};

/* assign counterReducer result to state.counter*/
var rootReducer = combineReducers({
  counter: counterReducer
});

/*
 * COUNTER COMPONENT
 */

var CounterComponent = function CounterComponent(props) {
  return React.createElement(
    'div',
    { className: 'counter-component' },
    React.createElement(
      'h2',
      null,
      'Superstitious counter component'
    ),
    React.createElement(
      'label',
      null,
      'Counter: ',
      props.counter
    ),
    React.createElement(
      'button',
      { type: 'submit', className: 'btn btn-default',
        onClick: props.increaseActionCreator },
      ' + '
    ),
    React.createElement(
      'button',
      { type: 'submit', className: 'btn btn-default',
        onClick: props.decreaseActionCreator },
      ' - '
    )
  );
};
/* INCOMING DIRECTION: map redux state.counter to component props.counter*/
function mapStateToProps(state) {
  return { counter: state.counter };
}
/* USE connect HOC to decorate CounterComponent with redux state and action creators*/
var ReduxCounterComponent = connect(mapStateToProps, { increaseActionCreator: increaseActionCreator, decreaseActionCreator: decreaseActionCreator })(CounterComponent);

/*
 * APP (MAIN) COMPONENT
 * simply renders ReduxCounterComponent
 */

var App = function (_React$Component) {
  _inherits(App, _React$Component);

  function App() {
    _classCallCheck(this, App);

    return _possibleConstructorReturn(this, (App.__proto__ || Object.getPrototypeOf(App)).apply(this, arguments));
  }

  _createClass(App, [{
    key: 'render',
    value: function render() {
      return React.createElement(
        'div',
        { className: 'app' },
        React.createElement(ReduxCounterComponent, null)
      );
    }
  }]);

  return App;
}(React.Component);

/*
 * MIDDLEWARE
 */

/*log called actions*/


var logger = function logger(_ref) {
  var dispatch = _ref.dispatch;

  return function (next) {
    return function (action) {
      console.log("ACTION CALLLED: ", action.type, " with payload: ", action.payload);
      next(action);
    };
  };
};

/*prevent to have a counter with value 13!!*/
var superstitiousMode = function superstitiousMode(store) {
  return function (next) {
    return function (action) {
      if (store.getState().counter + action.payload == 13) {
        var newAction = _extends({}, action, { payload: action.payload * 2 });
        store.dispatch(newAction);
      } else {
        next(action);
      }
    };
  };
};

/*
 * INDEX.JSX
 *  - create redux store with 'logger' middleware
 *  - assign store to Provider
 *  - render App (main) component in index.html ".container" element
 */

var createStoreWithMiddleware = applyMiddleware(logger, superstitiousMode)(createStore);

ReactDOM.render(React.createElement(
  Provider,
  { store: createStoreWithMiddleware(rootReducer) },
  React.createElement(App, null)
), document.querySelector('.container'));

Comments