Learn about me or read more of my blog
Written by Giulio Canti on 02 Feb 2015
In React 0.13 you no longer need to use React.createClass
to create React components:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
...
}
Counter.propTypes = { initialCount: React.PropTypes.number };
Counter.defaultProps = { initialCount: 0 };
(example from React’s Blog)
As you can see, propTypes are really just properties on the constructor:
Counter.propTypes = { initialCount: React.PropTypes.number };
There is another option: add type annotations to the constructor…
class Counter extends React.Component {
// example of propTypes as type annotations
constructor(props: { initialCount: number; }) {
super(props);
this.state = {count: props.initialCount};
}
...
}
// Counter.propTypes = { initialCount: React.PropTypes.number };
Counter.defaultProps = { initialCount: 0 };
…and use Flowcheck.
Flowcheck adds runtime asserts for each type annotation using a browserify transform:
# quick setup
npm install flowcheck
browserify -t flowcheck -t [reactify --strip-types --harmony] input.js -o output.js
If an assert fails the debugger kicks in so you can inspect the stack and quickly find out what’s wrong.
Flowcheck supports sourcemaps and there is flowcheck-loader (thanks @dan_abramov) for Webpack.
Check out the demo live