javascript reactjs

Telling if an element was created from a stateless functional component

I’m the owner of React Flip Move, a small library that helps animate transitions when DOM nodes are re-ordered.

It works by using refs; I clone the supplied children and attach a ref function that will grant me access to the underlying node, and I use that reference to imperatively animate as required.

Stateless functional components don’t support refs, though. When it’s passed an SFC, it throws an exception.

The current error message is super unhelpful, and I’d like to provide a more clear warning. The issue is, I don’t know how to tell if a React element was created from an SFC or not. Examining props.children, they look near-identical.

I can of course figure it out by wrapping the first call in a try/catch, but I’d like to be more explicit than that (also, I don’t want to wait until the first animation attempt before triggering the custom error message).

I don’t know if this helps but what do you think about this:

class StatefulComponent extends React.Component {...}
console.log(typeof StatefulComponent.prototype.isReactComponent); // logs 'object'
const StatelessComponent = () => {...}
console.log(typeof StatelessComponent.prototype.isReactComponent); // logs 'undefined'

However, I will try React Flip Move ASAP. Nice work!


So if you want to know if the children of your base component is a React Component:

// logs 'object' if it's a React Component otherwise logs 'undefined'
console.log(typeof this.props.children.type.prototype.isReactComponent);