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?
Props and PropTypes are important mechanisms for passing read-only attributes between React components. We can use React props, short for properties, to send data from one component to another. If a component receives the wrong type of props, it can cause bugs and unexpected errors in your app.
PropTypes are simply a mechanism that ensures that the passed value is of the correct datatype. This makes sure that we don't receive an error at the very end of our app by the console which might not be easy to deal with.
Flow is a static analysis tool which uses a superset of the language, allowing you to add type annotations to all of your code and catch an entire class of bugs at compile time. PropTypes is a basic type checker which has been patched onto React.
isRequired, // A required value of any data type requiredAny: PropTypes. any. isRequired, // You can also specify a custom validator. It should return an Error // object if the validation fails.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With