Skip to content

Instantly share code, notes, and snippets.

@samwgoldman
Last active April 3, 2021 22:20
Show Gist options
  • Select an option

  • Save samwgoldman/79d0da4bda25738c20c1 to your computer and use it in GitHub Desktop.

Select an option

Save samwgoldman/79d0da4bda25738c20c1 to your computer and use it in GitHub Desktop.
Pure, stateless, type-checked React components with Immutable.js and Flow
/* @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"} />
@nmn
Copy link
Copy Markdown

nmn commented Apr 19, 2015

good stuff.

@kolman
Copy link
Copy Markdown

kolman commented Apr 21, 2015

How would you pass callbacks?

@railsnerd
Copy link
Copy Markdown

Ah yeah callbacks scratches head

@samwgoldman
Copy link
Copy Markdown
Author

@kolman @railsnerd I don't understand the question. You just pass the callback as props. Flow can type functions, too.

@kahwee
Copy link
Copy Markdown

kahwee commented Apr 25, 2015

Is this in Typescript?

How did your props in React become Immutable objects? Is this an automatic thing?

Thanks for this example!

@rclai
Copy link
Copy Markdown

rclai commented Feb 4, 2016

@kahwee you have to pass them as Immutable objects already.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment