JSX is one of the core concepts of React. So if you understand it well, you will be able to write better React code.
In this tutorial, you will learn the syntax related to JSX and you will see some code examples of JSX to help illuminate the subject matter and drive the topic home.
What is JSX ?
JSX stands for JavaScript XML and it is basically a syntax extension of JavaScript.
It allows us to write HTML inside JavaScript which converts HTML tags into React Elements with the help of a transpiler, called Babel.
Why JSX is Required?
Using JSX is not compulsory but it is highly recommended for programming in React as it makes the development process easier as the code becomes easy to write and read.
With JSX:
import React from 'react'; function App() { return ( <div> <h1>Hello World!</h1> </div> ); } export default App;
As you can see in the first example, JSX allows us to write HTML directly within the JavaScript code.
Without JSX:
import React from 'react'; function App() { return React.createElement( 'div', null, React.createElement('h1', null, `Hello World!`) ); } export default App;
This is the same code written without JSX. So, JSX allows us to write HTML elements in JavaScript without using any createElement()
or appendChild()
methods.
As mentioned earlier you are not required to use JSX, but JSX makes it easier to write React applications. Each JSX element is just syntactic sugar for calling React.createElement
. So, anything you can do with JSX can also be done with just plain JavaScript.
Rules for Coding JSX
While writing JSX code you should keep the following things in mind.
Expressions in JSX
With JSX you can write expressions inside curly braces { }
.
The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result:
import React from 'react'; function App() { return <h1>The sum of 6 and 9 is {6 + 9}</h1>; //15 } export default App;
One Top Level Element
The HTML code must be wrapped in One top level element.
So if you like to write two paragraphs, you must put them inside a parent element, like a div
element.
// WRONG WAY function App() { return ( <h1>Hey, React!</h1> <h1>I love JSX!</h1> ); }
JSX will throw an error if the HTML is not correct, or if the HTML misses a parent element.
// CORRECT WAY import React from 'react'; function App() { return ( <div> <h1>Hey, React!</h1> <h1>I love JSX!</h1> </div> ); } export default App;
Alternatively, you can use a fragment to wrap multiple lines. This will prevent unnecessarily adding extra nodes to the DOM.
A fragment looks like an empty HTML tag: <> </>
import React from 'react'; function App() { return ( <> <h1>Hey, React!</h1> <h1>I love JSX!</h1> </> ); } export default App;
Inserting a Large Block of HTML
To write chunks of HTML on multiple lines, put the HTML inside parentheses.
import React from 'react'; function App() { return ( <div> <h1>Hello React!</h1> <p>I love JSX!</p> <p>This is a block of code. </p> </div> ); } export default App;
Elements Must be Closed
JSX follows XML rules, and therefore HTML elements must be properly closed.
// NOTICE THAT EVEN SELF CLOSING TAGS ARE PROPERLY CLOSED import React from 'react'; function App() { return ( <> <img src="img.png" alt="Yay" /> <input type="text" /> <br /> </> ); } export default App;
JSX will throw an error if the HTML is not properly closed.
JSX Attributes
The class
attribute is a much used attribute in HTML, but since JSX is rendered as JavaScript, and the class keyword is a reserved word in JavaScript, you are not allowed to use it in JSX.
JSX solved this by using className
instead. When JSX is rendered, it translates className
attributes into class
attributes.
import React from 'react'; function App() { return ( <> <h1 className="myclass">Hello World</h1> </> ); } export default App;
We can also use our own custom attributes in JSX. For custom attributes, we need to use data-
prefix. In the below example, we have used a custom attribute data-demoAttribute
as an attribute for the <p>
tag.
import React from 'react'; function App() { return ( <> <p data-demoAttribute="demo">Hello World!</p> </> ); } export default App;
In JSX, we can specify attribute values in two ways:
1. As String Literals:
We can specify the values of attributes in single or double quotes.
import React from 'react'; function App() { return ( <> <img className="avatar" src="https://i.imgur.com/7vQD0fPs.jpg" alt="Gregorio Y. Zara" /> </> ); } export default App;
Here, “https://i.imgur.com/7vQD0fPs.jpg” and “Gregorio Y. Zara” are being passed as strings.
2. As Expressions:
We can specify the values of attributes as expressions using curly braces {}
, but what if you want to dynamically specify the src
or alt
text? You could use a value from JavaScript by replacing ” and ” with { and }:
import React from 'react'; function App() { const avatar = 'https://i.imgur.com/7vQD0fPs.jpg'; const description = 'Gregorio Y. Zara'; return ( <> <img className="avatar" src={avatar} alt={description} /> </> ); } export default App;
Where to use curly braces:
You can only use curly braces in two ways inside JSX:
- As text directly inside a JSX tag:
<h1>{name}'s To Do List</h1>
works, but<{tag}>Gregorio Y. Zara's To Do List</tag>
will not. - As attributes immediately following the = sign:
src={avatar}
will read the avatar variable, butsrc="{avatar}"
will pass the string"{avatar}"
.
Conditions – if statements
React supports if statements, but not inside JSX.
To be able to use conditional statements in JSX, you should put the if statements outside of the JSX, or you could use a ternary expression instead:
Option 1: Write if statements outside of the JSX code
import React from 'react'; const x = 5; let text = 'Goodbye'; if (x < 10) { text = 'Hello'; } function App() { return ( <> <h1>{text}</h1> </> ); } export default App;
Option 2: Use ternary expressions instead
import React from 'react'; const x = 5; function App() { return ( <> <h1>{x < 10 ? 'Hello' : 'Goodbye'}</h1> </> ); } export default App;
Kindly note that in order to embed a JavaScript expression inside JSX, the JavaScript must be wrapped with curly braces, {}
.
Short-circuit Evaluation
In JavaScript, the &&
operator is known as the “logical AND“” operator, and it performs what’s known as short-circuit evaluation.
Given two expressions, it returns the value of the second expression if both expressions are truthy.
On the other hand, &&
will return the value of the first expression if either expression is falsy.
Let’s consider this code:
import React, { useState } from 'react'; import Welcome from '../components/Welcome'; function App() { const [showWelcome, setShowWelcome] = useState(false); return ( <> <div>{showWelcome ? <Welcome /> : null}</div> </> ); } export default App;
The code explains if a user is logged in, we want to greet them by rendering <Welcome/>
. If the user isn’t logged in, we don’t want to show anything.
So, in between the divs we have a ternary operator. A ternary operator is basically a shorthand for an if… else statement.
If showWelcome
is true then render <Welcome/>
or else render nothing.
But there’s a simpler way to do this using logical &&. Using the same logic, we can code the following:
import React, { useState } from 'react'; import Welcome from '../components/Welcome'; function App() { const [showWelcome, setShowWelcome] = useState(false); return ( <> <div>{showWelcome && <Welcome />}</div> </> ); } export default App;
The &&
logical operator means that both conditions on either side of it have to be met in order for it to be true.
Right now, as the code stands, showWelcome
is false because that’s what it’s initially set at by useState
. So nothing, or null
, would be rendered.
If it were set to true, however, both conditions would be successfully met and then render <Welcome/>
.
JSX Styling
To set inline styles in React, you need to use camelCase
syntax. React automatically allows appending px
after the number value on specific elements.
The following example shows how to use styling in the element.
import React from 'react'; function App() { var myStyle = { fontSize: 80, fontFamily: 'Courier', color: '#003300', }; return ( <> <h1 style={myStyle}>Hello World!</h1> </> ); } export default App;
Using “double curlies”: CSS and other objects in JSX
In addition to strings, numbers, and other JavaScript expressions, you can even pass objects in JSX. Objects are also denoted with curly braces, like { name: "Hedy Lamarr", inventions: 5 }
.
Therefore, to pass a JavaScript object in JSX, you must wrap the object in another pair of curly braces: person={{ name: "Hedy Lamarr", inventions: 5 }}
.
You may see this with inline CSS styles in JSX. React does not require you to use inline styles (CSS classes work great for most cases). But when you need an inline style, you pass an object to the style attribute:
import React from 'react'; function App() { return ( <> <ul style={{ backgroundColor: 'black', color: 'pink', }} > <li>Improve the videophone</li> <li>Prepare aeronautics lectures</li> <li>Work on the alcohol-fuelled engine</li> </ul> </> ); } export default App;
The next time you see {{
and }}
in JSX, know that it’s nothing more than an object inside the JSX curlies!
Kindly remember, inline style properties are written in camelCase.
For example, HTML <ul style="background-color: black">
would be written as <ul style={{ backgroundColor: 'black' }}>
in your component.
JavaScript Objects and Curly Braces
You can move several expressions into one object, and reference them in your JSX inside curly braces.
import React from 'react'; function App() { const person = { name: 'Gregorio Y. Zara', theme: { backgroundColor: 'black', color: 'pink', }, }; return ( <> <div style={person.theme}> <h1>{person.name}'s Todos</h1> <img className="avatar" src="https://i.imgur.com/7vQD0fPs.jpg" alt="Gregorio Y. Zara" /> <ul> <li>Improve the videophone</li> <li>Prepare aeronautics lectures</li> <li>Work on the alcohol-fuelled engine</li> </ul> </div> </> ); } export default App;
In this example, the person
JavaScript object contains a name
string and a theme
object:
const person = { name: 'Gregorio Y. Zara', theme: { backgroundColor: 'black', color: 'pink' } };
The component can use these values from person
like so:
<div style={person.theme}> <h1>{person.name}'s Todos</h1>
JSX is very minimal as a templating language because it lets you organize data and logic using JavaScript.
JSX Comments
JSX allows us to use comments that begin with /*
and ends with */
and wrapping them in curly braces {}
just like in the case of JSX expressions.
Below example shows how to use comments in JSX.
import React from 'react'; function App() { return ( <> <h1>Hello World!</h1> {/* This is a comment in JSX */} </> ); } export default App;
JSX Converter Tool
Converting all your existing markup can be tedious! We recommend using a converter to translate your existing HTML and SVG to JSX.
Tool: HTML to JSX Converter
Converters are very useful in practice, but it’s still worth understanding what is going on so that you can comfortably write JSX on your own.
Conclusion
In this article, we have seen how to use JSX in React. Here are some major takeaways:
- React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.
- JSX is similar to HTML, with a few differences. You can use a converter if you need to.
Thanks for reading!
Add comment