proper-component

Pass props to third-party React components, whether they expect them or not.

NPM version Build status Code style

Usage

Say you want to use this third-party component…

import React from 'react';

class Component extends React.Component {
  render() {
    return (
      <div className="component" style=>
        {this.props.children}
      </div>
    );
  }
}

export default Component;

…but it doesn’t allow forwarding of props it doesn’t care about (stopping you from adding things like ids or aria-*/data-* attributes), nor does it allow you to apply any extra classes or styles.

import React from 'react';
import { render } from 'react-dom';
import Component from 'third-party/Component';

render(
  <Component
    title="aww"
    className="utility-class"
    style=>
    Aww 😿
  </Component>,
  document.body
);

…will render[1]:

Aww 😿
<div class="component" style="color:tomato;font-style:italic">
  Aww 😿
</div>

Well, that sucks.

Now lets use proper-component to make a higher order component from Component, and suddenly, your wildest dreams become possible:

import React from 'react';
import { render } from 'react-dom';
import Component from 'third-party/Component';
import proper from 'proper-component';

const ProperComponent = proper(Component);

render(
  <ProperComponent
    title="yay"
    className="utility-class"
    style=>
    Yay 🎉
  </ProperComponent>,
  document.body
);

…will render[1]:

Yay 🎉
<div title="yay" class="component utility-class" style="color:thistle;font-style:italic;font-weight:bold">
  Yay 🎉
</div>;

(…yay)

Installation

npm install proper-component

FAQs / Notes

class ProperComponent extends React.Component {
  render() {
    const {className = '', style = {}, children ...props} = this.props;

    return (
      <div
        className={`component ${className}`}
        style=
        {...props}>
        {children}
      </div>
    );
  }
}

Maybe we can get third-party component library maintainers to do this in the first place, and we wouldn’t be in this situation in the first place. I look forward to proper-component’s reduncancy 🤞.

[1] Assume these global styles are already in the DOM:

.component {
  margin-bottom: 12px;
  border: 2px solid currentColor;
  padding: 6px 10px;
  background-color: papayawhip;
  font-family: sans-serif;
}
.utility-class {
  background-color: rebeccapurple;
}

Contributing

PRs are most welcome on GitHub!

If you clone this project & npm install its development dependencies, you can run tests with npm test and and hack on anything under /src.

I’ve not gotten around to seeing how this plays with project-specific development setups what use stuff like TypeScript/Flow, or PropTypes checking, so I’d love it if you shared your experiences, or throw a fix my way. Everybody benefits!

Authors