skip to Main Content

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


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

    Login or Signup to reply.
  2. JSX allows us to write HTML elements in JavaScript

    This is what JSX allows us.

    Doesn’t the {} brackets tell the compiler whatever is within the brackets is vanilla JS?

    This is what JSX really allows us.

    JSX lets you write HTML-like markup inside a JavaScript file, keeping rendering logic and content in the same place. Sometimes you will want to add a little JavaScript logic or reference a dynamic property inside that markup. In this situation, you can use curly braces in your JSX to open a window to JavaScript.

    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

    Why does the JS map function render JSX?

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search