I was wondering how NextJS successfully differentiates between JSX and JS in the following code. It is pretty simple but I was wondering how things worked under the hood. Specifically, I don’t understand how the JSX is successfully rendered. Doesn’t the {}
brackets tell the compiler whatever is within the brackets is vanilla JS? Why does the JS map function render JSX? (you can tell because the option
element uses className
instead of classname
). Then category
needs to be within brackets because it’s re-reverting to Javascript? Could someone explain how the compiler understands this? Thanks.
Code:
<div className={styles.shopAll}>
<select className={styles.dropdown}>
{categories.map((category, index) => (
<option
key={index}
value={category}
className={selectedCategory === category ? styles.active : ""}
onClick={() => handleCategoryClick(category)}
>
{category}
</option>
))}
</select>
2
Answers
I think there is confusion in terms of who is doing this work. JSX is parsed before NextJS by Webpack/Babel. Basically, this is just syntactic sugar over standard
React.createElemenet()
API calls.This might be a good start to explaining how it works.
https://react.dev/reference/react/createElement#creating-an-element-without-jsx
You can also try compiling it in a browser to have more clarity. Just copy-paste simple JSX components to have a better understanding.
https://babeljs.io/repl
This is what JSX allows us.
This is what JSX really allows us.
Take advantage of javaScript and the logic that can help, to create and return DOM elements (React elements).
you may not use javaScript but when you do, you have to return an element or an array of elemnts
JS map function basically returns an array, the most common usage is an array of objects, but in our case, it should be an array of HTML elements recognized as valid JSX elements (you just don’t break the rules).
In the other hand, javaScript recognizes HTML elements and it allows them to be push inside an array which can be returned latter, That’s great!
And this what the code does so this is OK
It is only React, and Nextjs uses React.