Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSX vs component class instancing

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 ?

like image 733
matt Avatar asked Jun 29 '17 12:06

matt


People also ask

What is the difference between a JSX element and a React component?

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.

Why do we use class components instead of functional components?

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).

What is JSX and why should I use it?

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:

What exactly is 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. Am I missing something here? Are they functionally different?


1 Answers

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.

like image 155
Adam LeBlanc Avatar answered Sep 27 '22 22:09

Adam LeBlanc