Skip to content

Use context to pass down redux and use decorators on smart components #245

Closed
@cgarvis

Description

@cgarvis

Love the ideas with redux. I haven't been able to dig into the actually code, but the API was bothering me a little so I've been play with some ideas. Think context and ES7 Decorators make for a better interface. Here are some code snippets demonstrating it.

Smart component would look like:

import autobind from 'autobind-decorator'

@autobind
@Redux
export default class CounterApp extends React.Component {
  render() {
    return (
      ...
     )
  }

  decrement() {
    this.dispatchAction(CounterActions.decrement);
  }

  increment() {
    this.dispatchAction(CounterActions.decrement);
  }
}

Redux mixin would look like:

export function Redux(Component) {
  Component.contextTypes = {
    dispatch: React.PropTypes.func.isRequired
  }

  Component.prototype.dispatchAction = function(action) {
    this.context.dispatch(action)
  }

  return Component
}

Redux Component and loading CounterApp

import autobind from 'autobind-decorator'

@autobind
class Redux extends React.Component {
  constructor() {
    this.state = {}
  }

  getChildContext() {
    return {
      dispatch: this.dispatch
    }
  }

  dispatch(action) {
    ...
  }

  render() {
    return React.cloneElement(this.props.children, this.state);
  }
}

Redux.childContextTypes = {
  dispatch: React.PropTypes.func
}

// Only allow one element on children
Redux.propTypes = {
  children: React.PropTypes.element.isRequired
}

ReactDOM.render(<Redux><CounterApp /></Redux>, document.body);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions