Using stateless functional components in React <= 0.13

One of the best new features included in React 0.14 is the stateless function component. A stateless function component is just a function that returns react elements.

function Square(props) {
return (
<Rectangle
width={props.size}
height={props.size}
{...props} />
);
};

Like I said, it’s just a function, but in React 0.14, you can call this function using JSX syntax.

ReactDom.render(<Square size='100' />);

This is really powerful, because it significantly reduces the boilerplate for simple components. But what if you’re not ready to upgrade your entire codebase to React 0.14 yet? After all, you just spent the last two months upgrading all of your components to version 0.13!

Wrap It

This problem is actually really easy to solve. All we have to do is create a higher order component that wraps around the stateless functional component. We can write a helper utility to create this class wrapper for us:

function toReactClass(func) {
return class FunctionalComponent extends React.Component {
static displayName = `FunctionalComponent(${func.name})`;
static defaultProps = func.defaultProps;
static propTypes = func.propTypes;
render() {
return func(this.props);
}
};
}

The function above creates a new class that wraps around the stateless functional component, behaving as an adapter so that old versions of React can render it.

It works!

Future Proof

The nice thing about this solution is that when you upgrade to React 0.14 (or higher), you can just remove the wrapper. You won’t need it anymore.

// React <=0.13
export default toReactClass(Square);
// React >=0.14
export default Square;

Or you could just leave it. It’s not hurting anything…

If you enjoyed this post or found it useful, please click the ♥ button below so that more people can see it!