Vic
Vic

Reputation: 8961

React composition component proptypes

I'm using the composition pattern for react. So, for example, I have this simple component:

class Simple extends React.Component {
  render() {
    return <div>{this.props.text}</div>;
  }
}

Simple.propTypes = {
  text: React.PropTypes.string.isRequired
};

Now, I have this enhanced component:

class Enhanced extends React.Component {
  render() {
    return (
      <div>
        <div>Hi, I'm the enhanced version</div>
        <Simple {...this.props} />
      </div>
    );
  }
}

Now, how can I specify the proptypes for the enhanced component? I could do this:

Enhanced.propTypes = {
  text: React.PropTypes.string.isRequired
};

but that's not good because I'll have to list all the props of Simple component and anytime I change those props, I'll have to change them in Enhanced

Upvotes: 3

Views: 1150

Answers (1)

azium
azium

Reputation: 20614

propTypes are just normal JS objects. You can compose them however you like:

// Simple.js
export const simplePropTypes = {
  text: React.PropTypes.string.isRequired
}

Simple.propTypes = simplePropTypes

// Enhanced.js
import Simple, { simplePropTypes } from './Simple'

Enhanced.propTypes = {
  somethingElse: React.PropTypes.number,
  ...simplePropTypes
}

update:

You should be able to use the component definition's propTypes directly.

Enhanced.propTypes = {
  somethingElse: React.PropTypes.number,
  ...Simple.propTypes
}

Upvotes: 5

Related Questions