Introducing JSX
7 minutes of reading
Consider the following variable declaration
const cutestAnimal = <p>Koala</p>;
This weird syntax is called JavaScript Syntax Extension (JSX), essentially, it's just a syntactic sugar which allows you to use HTML code within JavaScript. It is widely used in the React developer community as it makes our life much easier. You don't need to understand how they work under the hood for now, we will explore that very soon. Here, let's kick start by learning how to use it.
To be able to use this syntax, we need to import React from the react library.
import React from 'react';
JSX is included in the React library and is a syntactic sugar for the React.createElement method. When you are using JSX, Babel compiles JSX down to React.createElement calls.
Its prototype is the following. The first argument is the name of the type (it could be a HTML element or a React component), the second argument is the props of the type (you could omit that if you don't know what is a prop yet, we will discuss that later), all the arguments starting from the third argument are the children of the current type.
React.createElement(
type,
[props],
[...children]
)
For example, using JSX in the following way
1 2 3 4 5 6
function App() { return <div> <h1><span>Koalas are so cute~</span></h1> <h2>Do you agree?</h2> </div> }
is equivalent to the following
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import React from "react"; function App() { return React.createElement( "div", {}, React.createElement( "h1", {}, React.createElement("span", {}, "Koalas are so cute~") ), React.createElement("h2", {}, "Do you agree?") ); }
And the following
1 2 3
function App() { return <div className="koala"/> }
is equivalent to
1 2 3 4 5
import React from "react"; function App() { return React.createElement("div", { className: "koala" }); }
Just for completeness, we will show what is it compiled to when a React component is used. For those who don't know what a component is yet, you can think of it as a collection of HTML elements, <App /> is an example of a React component.
1 2 3 4 5 6 7 8 9 10 11 12
function App() { return ( <div> <h1>Koalas are so cute~</h1> <Button text="agree" /> </div> ); } function Button(props) { return <button>{props.text}</button>; }
is compiled to
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import React from 'react'; function App() { return React.createElement( "div", {}, React.createElement("h1", {}, "Koalas are so cute~"), React.createElement(Button, { text: "agree" }) ); } function Button(props) { return <button>{props.text}</button>; }