node package manager
We need your input. Help make JavaScript better: Take the 2017 JavaScript Ecosystem survey »

react-passthrough

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.