What is JSX in React?

What is JSX in React?

Everything you need to know about JSX to get started

What is JSX?

JSX, which stands for JavaScript XML, is one of Reacts best parts. JSX is a combination of HTML and JavaScript (JS). It's a way for us to write both HTML and JS in the same line, in one place. Look at these two examples:

HTML:

<h1>Hello World</h1>

JSX:

// regular JavaScript
const message = "Hello World"  

// JSX  
<h1>{message}</h1>

Here we have a basic example of JSX. We declare the variable message with the string value "Hello World". Then we display that variable directly in the JSX, and "Hello World" is rendered. This is the beauty of JSX.

Every time we have JavaScript code in our JSX, we need to use curly brackets "{}". That way, React knows that this is JS and needs to be calculated before we render the rest.

JSX can contain other form of JS as well. For example, we can use functions:

// regular JavaScript
const myName = (name) => {
  return name 
}

// JSX
<h1>{myName("Dave")}</h1>

Or, we could even use a variable as an argument in the function, like this:

// regular JS
const name = "Dave"
const myName = (name) => {
  return name 
} 
//JSX
<h1>{myName(name)}</h1>

Another way:

// A mix of JS and JSX
const message = <h1>Hello World</h1>

// JSX
<div>{message}</div>

Here you have a couple of different ways we use JSX in React, and there are many others examples you will come across in the future.

Why do we use JSX?

We use JSX because it makes the developer experience so much better and faster. Take this example:

Old school

// html file
<h1 class="header">Hello world</h1>

//  js file
const header = document.querySelector(".header")
header.textContent = "Hello another world"

React with JSX

// regular js
const newMessage = "Hello another world"

// JSX
<h1>{newMassage}</h1>

Not only is it less code to write, but you also almost never have to use document.querySelector anymore, which is a good enough reason for me. There are alot of different other examples, but that is for another time.

Rules of JSX

Here are some rules you should keep in mind when working with React:

  • JSX is simply a mix of HTML and JS. After React compiles the JSX, it will all end up as HTML.

  • All JavaScript code in your JSX needs to have curly brackets around {}.

  • When working with attributes or props, string values should be inside apostrof ("String here"), and everything else (functions, number, array, objects, variables...) should be in curly brackets {rest goes here}:

// JSX 
<div age={20} name="Dave" func={myFunction} car={carObject} animals={animalsArray}>
</div>
  • You can put all valid JavaScript Expressions inside your JSX

Closing

As always, if you have any comments, questions or I wrote something wrong, don't hesitate to comment/get in touch.

Did you find this article valuable?

Support Dave Kjell Marong by becoming a sponsor. Any amount is appreciated!