Is it OK to put propTypes and defaultProps as static props inside React class?

ffxsam picture ffxsam · Apr 21, 2016 · Viewed 27.7k times · Source

This is the way I've been doing it for quite some time now:

export default class AttachmentCreator extends Component {
  render() {
    return <div>
      <RaisedButton primary label="Add Attachment" />
    </div>
  }
}

AttachmentCreator.propTypes = {
  id: PropTypes.string,
};

But I've seen people doing it this way:

export default class AttachmentCreator extends Component {
  static propTypes = {
    id: PropTypes.string,
  };

  render() {
    return <div>
      <RaisedButton primary label="Add Attachment" />
    </div>
  }
}

And in fact I've seen people setting initial state outside the constructor as well. Is this good practice? It's been bugging me, but I remember a discussion somewhere where someone said that setting default props as a static is not a good idea - I just don't remember why.

Answer

dandel picture dandel · Apr 21, 2016

In fact, it's exactly the same in terms of performance. React.JS is a relatively new technology, so it's not clear yet what are considered good practices or don't. If you want to trust someone, check this AirBNB's styleguide:

https://github.com/airbnb/javascript/tree/master/react#ordering

import React, { PropTypes } from 'react';

const propTypes = {
  id: PropTypes.number.isRequired,
  url: PropTypes.string.isRequired,
  text: PropTypes.string,
};

const defaultProps = {
  text: 'Hello World',
};

class Link extends React.Component {
  static methodsAreOk() {
    return true;
  }

  render() {
    return <a href={this.props.url} data-id={this.props.id}>{this.props.text}</a>
  }
}

Link.propTypes = propTypes;
Link.defaultProps = defaultProps;

export default Link;

They are declaring a const with the propTypes object literals, keep the class pretty clean and assign them later to the static properties. I personally like this approach :)