About JSX

What is JSX?

JSX is a syntax extension to JavaScript, it looks a lot like HTML but is more strict.

Whenever there are curly braces used within JSX, it means that what is within the curly braces is a small bit of JavaScript code within the JSX code.

Back when interaction was a nice-to-have and not a must-have, HTML was the way to go. Now, with interactive websites, it's a great idea to have logic and markup rendered together in the same place, which will be in a component.

When you keep the rendering logic and markup together, it ensures that they stay in sync, even when they get edited.

Rules of JSX

  1. You have to return a single root element: If you are working with multiple elements inside of a component, they have to be wrapped in a single parent tag.

    • This can be div element.

    • This can also be a <> at the start and a </> at the end.

  2. You have to close all tags: You have to explicitly close all tags.

    • This means that self closing tags like <img> become <img /> .

  3. You have to use camelCase for everything: JSX will turn in to JavaScript code and attributes that are written in JSX will become keys of JavaScript objects.

    • Their names can not contain dashes or be reserved words like `class`.

JavaScript in JSX with Curly Braces

How to put JavaScript inside of JSX

Like mentioned before, you can use curly braces inside of JSX to add little pieces of JavaScript to your JSX. Some of the time however, it is not necessary.

Usually, when passing a string attribute to JSX, you can just put single or double quotes.

<img alt="Iris van Ollefen" />

But, if you want to make it more dynamic and use a JavaScript value, you can replace the quotes with curly braces.

<img alt={description} />

Where to use curly braces

One: when working with text:

// this will work
<h1>{name}'s To Do List</h1>

// this will not work
<{tag}>Iris van Ollefen</{tag}>

Two: when working with attributes:

// this will work
<img src={avatar} />
// this will read the avatar variable

// this will not work
<img src="{avatar}" />
// this will pass a string {avatar}

How to pass objects to JSX

You can actually pass more than just strings in JSX. You can even pass objects inside of curly braces.
But, since an object is already inside of curly braces, you will have to use double curly braces.

person={{ name: "Hedy Lamarr", inventions: 5 }}