-
-
Save ayozebarrera/a3d74c5ebb781e02de72 to your computer and use it in GitHub Desktop.
Pure, stateless, type-checked React components with Immutable.js and Flow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* @flow */ | |
var React = require("react") | |
var Immutable = require("immutable") | |
// In order to use any type as props, including Immutable objects, we | |
// wrap our prop type as the sole "data" key passed as props. | |
type Component<P> = ReactClass<{},{ data: P },{}> | |
type Element = ReactElement<any, any, any> | |
// Our componenets are truly a function of props, and immutability is | |
// assumed. This discipline is a feature, not a bug. | |
function component<P>(render: (props: P) => Element): Component<P> { | |
return (React.createClass({ | |
shouldComponentUpdate(props) { | |
return !Immutable.is(this.props.data, props.data) | |
}, | |
render() { | |
return render((this.props.data : any)) | |
} | |
}) : any) | |
} | |
// Defining components couldn't be simpler. | |
var Example: Component<string> = component((foo) => { | |
return <span>{foo}</span> | |
}) | |
// In order to use JSX, we need to pass our props as `data`, but flow | |
// will still type check this for us. | |
var foo = <Example data={"bar"} /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment