14

I'm using a library called react-forms in my React app. To better understand how it works I've been reading the code, but a convention keeps popping up which confuses me. Here's the ES6/JSX code:

'use strict';

var React = require('react/addons');
var cx = React.addons.classSet;

var Checkbox = React.createClass({

  propTypes: {
/...code.../
  },

  render(): ?ReactElement {
    /...code.../
  },

  onChange(e: {target: {checked: boolean}}) {
    /...code.../
  }
});

module.exports = Checkbox;

Note render(): ?ReactElement {}. That's the part which is confusing me. Could someone offer guidance on where to learn more about this syntax? I've hit a lot of dead ends via Google.

Dmitry Shvedov
  • 3,169
  • 4
  • 39
  • 51
Miles
  • 273
  • 3
  • 9
  • That's not ES6 syntax afaict. – Bergi Jan 31 '15 at 20:07
  • @Bergi `render():` is vanilla JS syntax? `onChange()` as well? I thought something like `render: function() {...}` would be needed. – Miles Feb 01 '15 at 14:35
  • 1
    Not either, yeah. As FakeRainBrigand answered, the `:` and the following declaration are for type checking. `render() { … }` is an ES6 method definition. – Bergi Feb 01 '15 at 14:41
  • @Bergi Thanks for your patience with my response; I'd thought you were referring to all of the code, not just the question mark... which was my main question to begin with, right? Derr. – Miles Feb 02 '15 at 05:59

1 Answers1

17

If you go to the package.json of react-forms, and look at the browserify section:

  "browserify": {
    "transform": [
      [
        "reactify",
        {
          "es6": true,
          "target": "es5",
          "stripTypes": true
        }
      ]
    ]
  },

stripTypes is enabled. It strips out things like ?ReactElement, which means it maybe returns a ReactElement (and otherwise null or undefined)

The {target: {checked: boolean}} means e has a target property, which has a checked property which is a boolean.

These are hints for the Flow type checker. You'll also see @flow in a comment at the top of all files that should be type checked. A type checker is a tool – like unit tests – that makes you more confident of your program's correctness, in a way that doesn't require manual testing. In many cases those little type annotations replace unit tests we'd otherwise write.

If you use flow in your project and try to do something like:

<Checkbox />

It would give you an type error because value and onChange are required props. Unlike the runtime props check, this happens without actually running the code (often as soon as you save the file).

Brigand
  • 84,529
  • 20
  • 165
  • 173