Higher order component to pass through unknown props to a child component.
JavaScript
Latest commit 48a8cb4 Jul 17, 2015 jamesknelson oops, added code fences to readme
Permalink
Failed to load latest commit information.
src initial commit Jul 14, 2015
.gitignore initial commit Jul 14, 2015
.npmignore initial commit Jul 14, 2015
README.md oops, added code fences to readme Jul 17, 2015
package.json initial commit Jul 14, 2015

README.md

react-passthrough

This code was featured in the article Building a property passthrough Higher-Order Component for React.

react-passthrough is a Higher-Order Component for React which adds a passthrough method to your classes. This method returns an object which contains all properties from this.propsexcept those specified in propTypes. It can be used as an ES7 class decorator.

The decorator can be configured with lists of properties to force passing of (regardless of being in propTypes), or to always omit.

Installation

Install with NPM:

npm install react-passthrough --save

Example usage

With ES7 decorators and class properties

import React from 'react'
import passthrough from 'react-passthrough'

@passthrough({force: ['disabled'], omit: ['children', 'form']})
class Control extends React.Component {
  static propTypes = {
    disabled: React.PropTypes.bool,
    className: React.PropTypes.className,
  }

  render() {
    let className = 'Control '
    if (this.props.disabled)  className += 'Control-disabled '
    if (this.props.className) className += this.props.className

    return (
      <div {...this.passthrough()} className={className}>
        {this.props.children}
      </div>
    )
  }
}

Without ES7

import React from 'react'
import passthrough from 'react-passthrough'

class Control extends React.Component {
  render() {
    let className = 'Control '
    if (this.props.disabled)  className += 'Control-disabled '
    if (this.props.className) className += this.props.className

    return (
      <div {...this.passthrough()} className={className}>
        {this.props.children}
      </div>
    )
  }
}

// Make sure to set propTypes before you run `passthrough`
Control.propTypes = {
  disabled: React.PropTypes.bool,
  className: React.PropTypes.className,
}

passthrough({force: ['disabled'], omit: ['children', 'form']})(Control)

How it works

When you run passthrough, react-passthrough immediately generates a list of properties to passthrough based on the value of the passed in component's propTypes, and the values of the force and omit options.

A passthrough method is then added to the component's prototype. This function then needs to be called within your render function to do the actual passthrough.