Can somebody explain to me the difference between the following two statements?
let test1 = new CustomComponent();
and
let test2 = <CustomComponent />
The debugger is Chrome gives me:
for test1
CustomComponent {props: undefined, context: undefined, refs: Object, updater: Object, state: Object…}
for test2
Object {$$typeof: Symbol(react.element), key: null, ref: null, props: Object, type: function…}
And how can I get a variable of type of test2, from of variable of the type of test1 ?
I understand the difference in syntax, however, this has made me realize that I do not understand the difference between a JSX element and a React component. As far as I can tell, a React component is basically a JSX element that is created by being returned by a nameless function, or by being returned by rendering through a class.
We used to use class components because of "state". In the older versions of React (version < 16.8), it was not possible to use state inside functional components. Therefore, we needed functional components for rendering UI only, whereas we'd use class components for data management and some additional operations (like life-cycle methods).
In the beginning, JSX might seem a little bit weird. But don't worry, you'll get used to it. JSX is very practical, because we can also execute any JavaScript code (logic, functions, variables, and so on) inside the HTML directly by using curly braces { }, like this:
As far as I can tell, a React component is basically a JSX element that is created by being returned by a nameless function, or by being returned by rendering through a class. Am I missing something here? Are they functionally different?
So.
let test1 = new CustomComponent();
is just a regular javascript thing, same thing happens as calling new thing()
any other time. Nothing special.
let test2 = <CustomComponent />
this is an JSX statement, and babel does some magic. It compiles <CustomComponent />
into React.createElement(CustomComponent , null)
. So, as you can see it is nothing like calling new
, it's calling a React function that creates an element, that react knows how to deal with.
Babel has a REPL tool that you can use to see what it's doing to your source code if you ever want to see quickly what's going on under the hood.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With