Want to determine if component is stateless/functional in React? Class components are inherently stateful, but with the introduction of React hooks functional components are no longer called stateless because they can be stateful, too.
isReactComponent special property exists on React.Component since React 0.14. This allows to determine whether a component is class component.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 ); } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.