Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does React know if a function component is a React component?

React supports both class and function components. All React files have an import React from ‘react’ statement at the top. When creating a class component (like so: class MyClassComponent extends React.Component ...), there is an explicit mention of which class this class instance extends from. However, when declaring a function component (const MyFunctionComponent = () => ()), it isn’t being explicitly said “hey this is a React component by the way.”

For all we know, this could be a function in plain JavaScript. How then, does React recognize functions as function components?

like image 792
jsdev17 Avatar asked Apr 09 '18 13:04

jsdev17


2 Answers

Here is the code for the isValidElement() function. In a nutshell, they check if it is an object (functions are objects) with a $$typeof of the REACT_ELEMENT_TYPE Symbol.

Beyond that though, it doesn't really matter if it is a normal function or not. For the most part, even if I make some random function, as long as it has a render() function, it'd be usable as a React element. I'm not sure if they have checks for missing lifecycle functions or not, but if they do, then it would work (if they don't, it'd throw errors).

When it comes to JavaScript "inheritence", it always just boils down to if the shape of the object matches the expected shape.

like image 50
samanime Avatar answered Sep 22 '22 15:09

samanime


It doesn't do that, every function is valid, if it returns a valid type. However, React doesn't check statically if a function will return something valid, so it just runs it, if it's a function. In newer React versions the return value can be nearly everything. Arrays work now, strings also. Currently React does support the following types as return values:

  • React elements. Typically created via JSX. An element can either be a representation of a native DOM component (), or a user-defined composite component ().
  • String and numbers. These are rendered as text nodes in the DOM.
  • Portals. Created with ReactDOM.createPortal.
  • null. Renders nothing.
  • Booleans. Render nothing. (Mostly exists to support return test && pattern, where test is boolean.)
  • Fragment (array of valid elements)

So, unless you don't return undefined, it should work, but as said, it will execute it always if it is a function.

like image 27
Armin Šupuk Avatar answered Sep 26 '22 15:09

Armin Šupuk