DEV Community

Pavol Ďuďák
Pavol Ďuďák

Posted on • Edited on

What hides under JSX

I finally pushed myself to write next post so, here it is.

So, JSX. A really familiar, simple and handy thing for writing components in React. But markup in JS? Kinda weird no? Well, it’s not markup but valid JS expressions, after transpilation just function calls that evaluates to objects, objects representing React components. Let’s grab a simple component:

Just a simple picture frame for grid gallery. The first thing you will probably notice is className. In HTML it’s just class but here, because naming conflict with JS class keyword it is className. All attributes are in camelCase in JSX.
JSX is only expressions remember? That is one of the reasons why camelCase is used. Let’s move on.
One really important thing to remember for components is to return only ONE React element. Here img tag is enclosed within div tag.
In bigger components where you need to return multiple tags (components) the React approach is to enclose elements in React.Fragment tag or shorter version just empty tag. React will notify you about this if you don't do it. It prevents appending redundant tags in DOM that can sometimes produce invalid HTML.
But how is JSX just JS expressions? You can write the same JSX just like this:

And this is what transpiler does to our JSX. Just transforms it into this so it can be appended to virtual DOM, but that is a whole other topic.
You can see how ugly nested and verbose can components get without JSX. As in the first snippet when we are setting src in img tag prop pic is enclosed in { curly braces }. All JS expressions in JSX must be enclosed in { curly braces } so React can tell what to render and what to evaluate as JS. Probably the last thing is that as in the previous sentence I’ve said “All JS expressions” emphasis on expression. You can’t use if statement, for or while loops in JSX. But, we can substitute if statements with ternary expressions and since glorious ES6 loops with calling map, forEach, etc. on arrays. Heres an example of map function and usage of our first component:

Somewhere where this snippet lives we have an array of objects including links to dog pictures called ‘doggos’. We are calling map function on this array (which as you probably know iterates through the array and applies provided a function on every element and returns new array). The returns part is important since in JSX we are using only expressions that evaluate to something in our case a new array containing React components.
I hope that my explanation vas understandable and maybe can help someone to better understand React. Also, any questions are welcome.
Thank you for getting to the end of this post. You can suggest in the comments what you want next :)

Top comments (0)