Context Wrapper

It is a good practice that our context is not just a plain object but it has an interface that allows us to store and retrieve data. For example:

  1. // dependencies.js
  2. export default {
  3. data: {},
  4. get(key) {
  5. return this.data[key];
  6. },
  7. register(key, value) {
  8. this.data[key] = value;
  9. }
  10. }

Then, if we go back to our example, the very top App component may look like that:

  1. import dependencies from './dependencies';
  2. dependencies.register('title', 'React in patterns');
  3. class App extends React.Component {
  4. getChildContext() {
  5. return dependencies;
  6. }
  7. render() {
  8. return <Header />;
  9. }
  10. }
  11. App.childContextTypes = {
  12. data: PropTypes.object,
  13. get: PropTypes.func,
  14. register: PropTypes.func
  15. };

And our Title component gets it’s data through the context:

  1. // Title.jsx
  2. export default class Title extends React.Component {
  3. render() {
  4. return <h1>{ this.context.get('title') }</h1>
  5. }
  6. }
  7. Title.contextTypes = {
  8. data: PropTypes.object,
  9. get: PropTypes.func,
  10. register: PropTypes.func
  11. };

Ideally we don’t want to specify the contextTypes every time when we need an access to the context.
This detail may be wrapped in a higher-order component.
And even more, we may write an utility function that is more descriptive and helps us declare the exact wiring.
ie. instead of accessing the context directly with this.context.get(‘title’) we ask the higher-order component to
get what we need and to pass it as a prop to our component.
For example:

  1. // Title.jsx
  2. import wire from './wire';
  3. function Title(props) {
  4. return <h1>{ props.title }</h1>;
  5. }
  6. export default wire(Title, ['title'], function resolve(title) {
  7. return { title };
  8. });

The wire function accepts first a React component, then an array with all the needed dependencies
(which are registered already) and then a function which I like to call mapper.
It receives what’s stored in the context as a raw data and returns an object which is the actual
React props for our component (Title). In this example we just pass what we get - a title string variable.
However, in a real app this could be a collection of data stores, configuration or something else.
So, it’s nice that we pass exactly what we need and don’t pollute the components with data that they don’t need.

Here is how the wire function looks like:

  1. export default function wire(Component, dependencies, mapper) {
  2. class Inject extends React.Component {
  3. render() {
  4. var resolved = dependencies.map(this.context.get.bind(this.context));
  5. var props = mapper(...resolved);
  6. return React.createElement(Component, props);
  7. }
  8. }
  9. Inject.contextTypes = {
  10. data: PropTypes.object,
  11. get: PropTypes.func,
  12. register: PropTypes.func
  13. };
  14. return Inject;
  15. };

Inject is a higher-order component that gets access to the context and retrieves all the items listed under dependencies array.
The mapper is a function receiving the context data and transforms it to props for our component.

Non-context alternative

Use a singleton to register/fetch all dependencies

  1. var dependencies = {};
  2. export function register(key, dependency) {
  3. dependencies[key] = dependency;
  4. }
  5. export function fetch(key) {
  6. if (key in dependencies) return dependencies[key];
  7. throw new Error(`"${ key } is not registered as dependency.`);
  8. }
  9. export function wire(Component, deps, mapper) {
  10. return class Injector extends React.Component {
  11. constructor(props) {
  12. super(props);
  13. this._resolvedDependencies = mapper(...deps.map(fetch));
  14. }
  15. render() {
  16. return (
  17. <Component
  18. {...this.state}
  19. {...this.props}
  20. {...this._resolvedDependencies}
  21. />
  22. );
  23. }
  24. };
  25. }

We’ll store the dependencies in dependencies global variable (it’s global for our module, not at an application level).

We then export two functions register and fetch that write and read entries.

It looks a little bit like implementing setter and getter against a simple JavaScript object.

Then we have the wire function that accepts our React component and returns a higher-order component.

In the constructor of that component we are resolving the dependencies and later while rendering the original component we pass them as props.

We follow the same pattern where we describe what we need (deps argument) and extract the needed props with a mapper function.

Having the di.jsx helper we are again able to register our dependencies at the entry point of our application (app.jsx) and inject them wherever (Title.jsx) we need.

  1. // app.jsx
  2. import Header from './Header.jsx';
  3. import { register } from './di.jsx';
  4. register('my-awesome-title', 'React in patterns');
  5. class App extends React.Component {
  6. render() {
  7. return <Header />;
  8. }
  9. }
  1. // Header.jsx
  2. import Title from './Title.jsx';
  3. export default function Header() {
  4. return (
  5. <header>
  6. <Title />
  7. </header>
  8. );
  9. }
  1. // Title.jsx
  2. import { wire } from './di.jsx';
  3. var Title = function(props) {
  4. return <h1>{ props.title }</h1>;
  5. };
  6. export default wire(Title, ['my-awesome-title'], title => ({ title }));

If we look at the Title.jsx file we’ll see that the actual component and the wiring may live in different files.
That way the component and the mapper function become easily unit testable.