foxhound87
5/7/2016 - 9:24 PM

State Management & Hydration with MobX [Ep. 05] /src/state/context.js

State Management & Hydration with MobX [Ep. 05] /src/state/context.js

import React, { Component } from 'react';
import { observer } from 'mobx-react';

const contextTypes = {
  router: React.PropTypes.object, // react-router
  store: React.PropTypes.object, // our stores
};

export class ContextProvider extends Component {

  static propTypes = {
    children: React.PropTypes.node,
    context: React.PropTypes.shape(contextTypes),
  };

  static childContextTypes = contextTypes;

  getChildContext() {
    return this.props.context;
  }

  render() {
    return this.props && this.props.children;
  }
}

/**
 * Decorate components with context and observable
 * @param component
 * @returns {Function|Class}
 */
export function connect(component) {
  if (!component) return contextTypes;
  Object.assign(component, { contextTypes });
  return observer(component);
}