What does JSX code look like when converted to JavaScript? Let's look at it in the next video.
In this video, you looked at the syntax of the React.createElement() method as mentioned below:
React.createElement(element_name, element_properties, children);
The first argument in this method is the name of the element that is to be rendered. This can be either your custom component or an HTML element. The second argument is the object that consists of property-value pairs that can be provided as attributes to this component or element. After these two arguments, you can pass an infinite number of children elements, which will be nested inside this main component or element. These children can, in turn, have other children elements nested inside them.
The first argument is mandatory, while the rest of the arguments that follow are optional.
You have also looked at a couple of examples about how JSX code gets converted to JavaScript code using React.createElement(). One such example is given below:
JSX code:
<div id="module"> <p>ReactJS</p> </div>
JavaScript code:
React.createElement("div", {id: "module"}, React.createElement("p", null, "ReactJS") );
Now is the time to run JSX and its equivalent JavaScript code and see if there’s any difference between the two. Let’s do this inside the Phone Directory application you created.
As shown in the video, both the code snippets given above do the exact same thing. When you try to write the aforementioned JSX code, Babel converts it into JavaScript code, which is given below it.
Look at the screenshot (taken from Babel.io) given below to get an idea of how fewer lines of JSX code get converted to a lot of lines of JavaScript code:
Again, this is just a small example. What about when you need to render a large element consisting of multiple children elements or render an entire webpage starting with the main container inside the body element? Would you prefer writing a JavaScript code containing hundreds of lines for it or the JSX (HTML-like) code using fewer lines? Well, the smart choice is very obvious!
Finally, it’s time to look at the behind-the-scenes logic of an important thing that we have been discussing. To know more, watch the next video.
In this entire segment, you learned that whenever you use JSX to render DOM elements, the JSX code for the element gets converted to the React.createElement() method in JavaScript. You also looked at its syntax and some examples.
Time to exercise your brain!