React Context Demo

In this example below you will see how to do a React Context Demo with some HTML / CSS and Javascript

Using React Context API with React 16.4 Blog post here: https://codepen.io/adamaoc/post/react-context-api-roundtable

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

Technologies

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

<head>
  <meta charset="UTF-8">
  <title>React Context Demo</title>
  
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

  
      <style>
      /* NOTE: The styles were added inline because Prefixfree needs access to your styles and they must be inlined if they are on local disk! */
      * {
  box-sizing: border-box;
}

body {
  display: flex;
  justify-content: center;
}

.dealer-page {
  background: #eee;
  padding: 3em 1em;
  width: 300px;
  border-radius: 3px;
  box-shadow: 1px 2px 8px #888;
}
.dealer-page p {
  display: flex;
  align-items: center;
}
.dealer-page button {
  margin-left: auto;
  background: cornflowerblue;
  border: none;
  color: #fff;
  padding: 0.5em;
  border-radius: 5px;
}

em {
  color: #888;
  font-size: 0.75rem;
}

    </style>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

</head>

<body>

  <div id="app"></div>
  <script src='https://unpkg.com/react@16/umd/react.development.js'></script>
<script src='https://unpkg.com/react-dom@16/umd/react-dom.development.js'></script>

  

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




</body>

</html>

/*Downloaded from https://www.codeseek.co/adamaoc/react-context-demo-YLdQmL */
* {
  box-sizing: border-box;
}

body {
  display: flex;
  justify-content: center;
}

.dealer-page {
  background: #eee;
  padding: 3em 1em;
  width: 300px;
  border-radius: 3px;
  box-shadow: 1px 2px 8px #888;
}
.dealer-page p {
  display: flex;
  align-items: center;
}
.dealer-page button {
  margin-left: auto;
  background: cornflowerblue;
  border: none;
  color: #fff;
  padding: 0.5em;
  border-radius: 5px;
}

em {
  color: #888;
  font-size: 0.75rem;
}


/*Downloaded from https://www.codeseek.co/adamaoc/react-context-demo-YLdQmL */
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; }

var DealerContext = React.createContext();

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

  function DealerProvider() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, DealerProvider);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = DealerProvider.__proto__ || Object.getPrototypeOf(DealerProvider)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      name: 'New Dealer',
      dealerId: 1234,
      groupId: 1,
      editing: false
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(DealerProvider, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      return React.createElement(
        DealerContext.Provider,
        { value: {
            state: this.state,
            updateDealerName: function updateDealerName(value) {
              _this2.setState({ name: value.target.value });
            },
            toggleEditing: function toggleEditing() {
              if (_this2.state.editing) {
                _this2.setState({ editing: false });
              } else {
                _this2.setState({ editing: true });
              }
            }
          } },
        this.props.children
      );
    }
  }]);

  return DealerProvider;
}(React.Component);

var DealerProfile = function (_React$Component2) {
  _inherits(DealerProfile, _React$Component2);

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

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

  _createClass(DealerProfile, [{
    key: "render",
    value: function render() {
      return React.createElement(
        "div",
        { className: "dealer-profile" },
        React.createElement(
          DealerContext.Consumer,
          null,
          function (context) {

            var btnText = "edit";
            if (context.state.editing) {
              btnText = 'save';
            }
            return React.createElement(
              React.Fragment,
              null,
              React.createElement(
                "p",
                null,
                "Name: ",
                context.state.name,
                React.createElement(
                  "button",
                  { onClick: context.toggleEditing },
                  btnText
                )
              ),
              React.createElement(
                "p",
                null,
                "Dealer ID: ",
                context.state.dealerId
              )
            );
          }
        )
      );
    }
  }]);

  return DealerProfile;
}(React.Component);

var DealerActions = function (_React$Component3) {
  _inherits(DealerActions, _React$Component3);

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

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

  _createClass(DealerActions, [{
    key: "render",
    value: function render() {
      var _this5 = this;

      return React.createElement(
        DealerContext.Consumer,
        null,
        function (context) {
          return React.createElement(
            React.Fragment,
            null,
            context.state.editing ? React.createElement("input", {
              type: "text",
              defaultValue: context.state.name,
              onChange: context.updateDealerName.bind(_this5) }) : null
          );
        }
      );
    }
  }]);

  return DealerActions;
}(React.Component);

var DealerCard = function DealerCard() {
  return React.createElement(
    "div",
    { className: "dealer-page" },
    React.createElement(DealerProfile, null),
    React.createElement(DealerActions, null)
  );
};

var DealerApp = function (_React$Component4) {
  _inherits(DealerApp, _React$Component4);

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

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

  _createClass(DealerApp, [{
    key: "render",
    value: function render() {
      return React.createElement(
        DealerProvider,
        null,
        React.createElement(
          "h1",
          null,
          "Dealer Card"
        ),
        React.createElement(DealerCard, null),
        React.createElement(
          "p",
          null,
          React.createElement(
            "em",
            null,
            "Using React Context API with React 16.4"
          )
        )
      );
    }
  }]);

  return DealerApp;
}(React.Component);

ReactDOM.render(React.createElement(DealerApp, null), document.getElementById('app'));

Comments