JSX is syntactic sugar (available in the React library) that makes it easy to develop apps.
Let’s learn how to use it.
JSX stands for JavaScript + XML. It is written like this
const divElt = <div>Hello World</div>;
Don’t think of it as HTML
, but as a kind of template language with the full power of JavaScript.
With this new syntax, React has ‘broken’ the traditional dogma of building web sites or apps, i.e., separation of concerns: markup (HTML), style (CSS), behavior (JS).
You can even use any JS operator or expression, and more, with JSX.
const target = 'Africa'
const divElt = <div>Hello, {target}</div>;
When using JSX, notice that it calls React.createElement()
Given our initial code written with JSX:
const divElt = <div>Hello World</div>;
Without JSX, it will look like this:
React.createElement(
'div',
'Hello World'
)
You may notice that we aren’t yet talking about rendering here!
Time for practice.
Warning:
Be aware that JSX is not regular JS. As a consequence, a browser cannot execute JS files that contain JSX code. If you’re working offline or using React with thescript
tag, make sure that you addBabel
in your project.
import React from 'react'; import ReactDOM from 'react-dom'; const target = 'Africa' const divElt = <div>Hello, {target}</div>; ReactDOM.render( divElt, document.getElementById('root') );
It is not mandatory to use JSX when writing React code, but JSX is highly recommended and has been massively adopted by the community.
Here are some reasons:
Tips:
- To comment in JSX:
{/* This is a comment */}
- To add a
class
property:const divElt = <div className="greeting">Hello World</div>;
In this tutorial, we have learned that JSX provides syntactic sugar for the React.createElement()
API. It is concise and let us combine everything (HTML, CSS, JS) in our component. It requires Babel
to be transpiled into plain JavaScript.