Bogdan-Lyashenko/Under-the-hood-ReactJS

How does react know that a stateless function is a react component

DianaSuvorova opened this issue · 5 comments

First of all thanks for publishing this. This looks like an enormous effort that would benefit a lot of people.

I am working on a few issues for https://github.com/yannickcr/eslint-plugin-react library and have very specific question that you might have an answer for.

How does react know that a stateless function is a react component.
For example:

const statelessComponent = (props) => {
   return <span>{props.someProp}</span>;
 }

If you could point to a source code where react evaluate whether a function is a React or not that would be awesome. Any other directions would also be greatly appreciated

Thanks,
Diana

Actually, as I typed it I realized that this wouldn't be react it would be babel that would do the work.
More specifically babel react preset.

I will look into it to see how they do it.

@DianaSuvorova , I don't think it's a babel. Support of stateless functional components was added in some of the old versions, but it hadn't been like that from the very beginning.

What do you actually mean by 'how does React know'? It doesn't :) I mean, it's not a React component till it's not pasted into other component's render method or ReactDOM.render. Then a ReactElement configuration object will be created for it and after a ReactCompositeComponent object will be instantiated from that configuration object.

Here is how it works:

  1. During parsing JSX from component's render method, JSX tags will be replaced by React.createElement calls, but in fact, you can put React.createElement(statelessComponent, ...) directly and it will work (https://facebook.github.io/react/docs/react-without-jsx.html) fine.

  2. React.createElement will create an object like

{
	$$typeof: Symbol(react.element),
	key: null,
	props: {props...},
	ref: null, 
	type: ƒ statelessComponent(props),
	...
}
  1. Then, during mounting of its parent the ReactCompositeComponent isntance will be created (by function instantiateReactComponent). 'Function' type of ReactElement is treated in the same way as a class, so ReactCompositeComponent is a mirror component for it.

So, the thing is React allows you to pass into React.createElement function as type (besides of class, etc.) and knows how to handle it further.

@Bogdan-Lyashenko

What do you actually mean by 'how does React know'? It doesn't :) I mean, it's not a React component till it's not pasted into other component's render method or ReactDOM.render.

That explains it! So react only knows it during runtime. I was looking for a static analysis method. But this makes sense!
Can you please point me to the source code for the React.createElement (or your documentation of it)? Where it creates the object you described.

Thank you!

Thank you!