React - how to determine if a component is stateless / functional?

I have a functional / non-stationary component and a component inherited from React.Component :

 const Component1 = () => (<span>Hello</span>) class Component2 extends React.Component { render() { return (<span>Hello</span>) } } 

How to determine if a component is stateless or not? Is there an official way?

 isStateless(Component1) // true isStateless(Component2) // false 
+14
javascript reactjs
source share
3 answers

you can check its prototype, for example:

 function isStateless(Component) { return !Component.prototype.render; } 
+14
source share

Class components are inherently states, but with the advent of React hooks, functional components are no longer called stateless because they can also be composed.

The special property isReactComponent exists in React.Component since React.Component 0.14. This allows you to determine whether a component is a component of a class.

 function isFunctionalComponent(Component) { return ( typeof Component === 'function' // can be various things && !( Component.prototype // native arrows don't have prototypes && Component.prototype.isReactComponent // special property ) ); } function isClassComponent(Component) { return !!( typeof Component === 'function' && Component.prototype && Component.prototype.isReactComponent ); } 

Similar checks are performed in the React code base.

Since components can be various things, such as a Context Provider or a Consumer , isFunctionalComponent(Component) may not be equal to !isClassComponent(Component) .

+4
source share

Depends on what is called "stateless persons." If a stateless person means "cannot be ref ", then this:

 function isStateless(Component) { return typeof Component !== 'string' && !Component.prototype.render } 

Update: A new type of PropTypes.elementType for React components (not "elements") has also appeared.

+2
source share

All Articles