Chris Chris - 22 days ago 7
React JSX Question

Should Reacts `propTypes` and `defaultProps` be used in conjunction with Flowtype, or is Flowtype comprehensive enough?

Thinking of a simple example such as:

class CommentAreaComponent extends React.Component {
static propTypes = {
id: PropTypes.string.isRequired,
loading: PropTypes.bool,
};

static defaultProps = {
loading: false,
};


In the constructor I can define something like this to achieve (I think) the same thing:

class MyComponent extends React.Component {
constructor({
loading = false,
}:{
id:string,
loading?:boolean
}) {
super(arguments[0]);
}
}


The second example is using only Flowtype. Does using Reacts PropTypes and DefaultProps offer an advantage? Or can I drop them completely when using FlowType?

Answer

You can surely use Flow types instead of React PropTypes, but your proposed syntax is not the common way to do it. See Flow docs (scroll down for ES6 syntax):

class Button extends React.Component {
  props: {
    title: string,
    visited: boolean,
    onClick: () => void,
  };

  state: {
    display: 'static' | 'hover' | 'active';
  };

  static defaultProps = {
    visited: false,
  };

  constructor(props) {
    super(props);
    this.state = {
      display: 'static',
    };
  }

  render() {
    let className = 'button ' + this.state.display;
    if (this.props.visited) {
      //...
    }

    return (/*...*/);
  }
}

The only thing you can't do with Flow types that you can do with PropTypes is defining custom validators (e.g. to check that a prop is a valid email).

I have more Flow React examples on github, but I didn't test them with Flow v0.22 yet, only v0.21. They might need minor adjustments.