Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 911
Joshua Comeau Avatar asked Nov 12 '16 13:11

Joshua Comeau


People also ask

Is functional component stateless component?

A functional component is always a stateless component, but the class component can be stateless or stateful. There are many distinct names to stateful and stateless components.

What is a stateless functional component?

Updated May 22, 2022. A stateless function component is a typical React component that is defined as a function that does not manage any state. There are no constructors needed, no classes to initialize, and no lifecycle hooks to worry about. These functions simply take props as an input and return JSX as an output.

Can stateless components have state?

Stateless components, by contrast, have no state. Note that both types of components can use props. In the example, there are two React components. The Store component is stateful and the Week component is stateless.

Can stateless components have props?

A component can be stateless and only use the props values passed to it. These values can either contain references to a calling component's state values or references to a calling component's method.


1 Answers

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!

EDIT:

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); 
like image 188
Seb Bizeul Avatar answered Nov 15 '22 18:11

Seb Bizeul