Deep Understanding of JSX

Deep Understanding of JSX

Basics of JSX and how to use it?

What does JSX do?

A component is react is rendered with both computational part (like JavaScript) as well as presentational part(like HTML).

JSX is that syntax that helps us to achieve our objectives but the browser doesn't understand JSX, so, when we call JSX then in the background React calls the createElement which creates an object structure that is easily understood by the browser.

Consider the picture below:

In this part, we have called JSX but internally the JSX has called createElement which can easily be understood by the browser.

Consider the picture below:

Here we can see the internal implementation of the JSX. Here it is calling createElementID which passes three values which are type(h1-in this case), attribute(attribute - null in this case) and component("JSX is awesome" in this case). Here we have manually done the internal implementation. It might look simple because we only have h1 tag here but the moment code starts getting complex you will start to hate createElementID method.

Consider the picture below:

In this code snippet, we can see the creation of an object in the console of the browser.

Consider the picture below:

Here you can clearly see in the console that in line 7(from the left code snippet) JSX does the internal implementation and creates an object internally whereas in line 10(from the left side code snippet) you can see that we have manually created an object which can be verified by the console(in the right side). Both examples do the same thing. So why should we do the implementation manually when it can be done internally by JSX.

Let's see a bit complex HTML structure.

Here you can see the creation of an object with its properties, children etc.

I hope by this time you would've started to appreciate JSX.


JavaScript in JSX

To use JS in JSX we need to use curly brackets{} which is termed as an expression.

Now you can declare anything in the const topic, you will notice that the output changes according to your input.


How to use Boolean in JSX?

Consider the picture below

To use Boolean in JSX you will have to typecast it with String. You cannot simply use an expression to render a boolean in JSX.


How to use conditions and loops in JSX?

In JSX you cannot use the traditional if-else syntax. In JSX you can use ternary operators to apply conditions in your code.

To use loops in JSX you cannot use for-loop, while-loop or do-while-loop for that matter. You have to use the map function of Js in JSX as well.


This was the end of this blog.

I hope you could grasp the idea of what JSX is and hopefully, you appreciate it now.

Thank you for giving your time. Do comment with your valuable feedback.