React is a popular JavaScript library for building user interfaces. It was created by Facebook and released to the public in 2013. Since then, it has gained widespread adoption in the tech industry and is used by many companies, big and small, to build web and mobile applications.
One of the reasons for React's popularity is its ability to create complex and dynamic user interfaces with ease. React uses a syntax called JSX (JavaScript XML) allowing developers to write HTML-like code within JavaScript, making it easier to reason about the structure and behavior of their applications.
In this article, we will delve into the details of JSX and explore how it makes React such a powerful tool for building dynamic and engaging user interfaces.
Pre-requisites
To follow along through this article you are required to have:
- Basic knowledge of HTML
- Knowledge in Javascript
- Basic React skills
Introduction
JSX is a syntax extension to Javascript and is used with React to describe how the user interface should look like. This enables React to utilize declarative aspect of programmming. You might find the word declarative a bit complex but don't worry we are going to cover it in this article.
To understand the role of JSX in React we will take a look at how we create HTML elements in plain JavaScript then look at how they are created in React.
We will cover:
- Imperative vs Declarative Programming
- Creating HTML elements in Vanilla JavaScript
- Creating HTML elements in React
- Nesting in JSX
Imperative vs Declarative Programming
Suppose you wish for someone to prepare a cake for breakfast. You have two options:
Firstly, you can simply request the baker to bake, assuming they know how to do it, and omit giving any instructions on the baking process. Alternatively, you can still request the cake but also provide the baker with instructions on how to go about the baking process.
Imperative programming is a software development paradigm where functions are implicitly coded in every step required to solve a problem while declarative programming is a paradigm which utilizes abstraction of the control flow behind how a particular solution is achieved.
Declarative describes what you want to do not how you want to do it.
The idea about giving instructions on how something should be done explains the imperative aspect of programming while the other explains declarative aspect of programming.
Creating HTML elements in Vanilla JavaScript
Before we get into how JSX is used in React applications, we will first get to understand how it is done in pure JavaScript.
Create an index.html file and paste the code below and open it in your browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>The Document Object Model</h1>
<h2>The createElement() Method</h2>
<p>Create a p element and append it to the div with id "myDiv"</p>
<div id="myDiv" style="padding: 16px; background-color: paleturquoise;">
<h3>My Div</h3>
</div>
<script>
// create HTML element
const paragraph = document.createElement("p");
paragraph.innerHTML = "Created a paragraph using JS."
// append to the myDiv div
document.getElementById("myDiv").appendChild(paragraph)
</script>
</body>
</html>
createElement
creates the HTML element specified by the tagName which is its parameter.
appendChild
on the other hand adds the node or rather element created to the end of the list of children of the specified parent ('myDiv' in our case) node.
If you understood the two programming paradigms above you will categorize this as an imperative programming because we are implicitly giving instructions on how it should be done.
Creating HTML elements in React
In React, JSX is a syntax extension recommended to describe how the user interface should look like.
To further understand how this happens, we are going to create a simple React application by pasting the code below on our terminal.
npx create-react-app jsx-demo
cd jsx-demo
npm start
You can edit the src/App.js file by pasting the code below
import React from "react"
function App() {
const h1Title = <h1 className="h1title">JSX in a nutshell</h1>
return(
h1Title
)
}
export default App
In JavaScript, we cannot assign HTML elements to values as shown above, however, in React, JSX gives us the power to do that.
Since almost everything in JavaScript is an object the h1Title
is also an object and we can log it to see what it contains.
Just below the h1Title assignment you can add console.log(h1Title)
{
type: 'h1',
props: {
className: 'h1title',
children: 'JSX in a nutshell'
}
}
The above is a cleaner view of the result which you are seeing on the console after inspecting your application. This representation is what is known as a React Element
which represents the final HTML output as a plain object.
Each node in the JSX is a plain object describing a component instance or a DOM node and its desired properties(props).
The two main attributes of the React Element is the type
which defines the type of node and the props
which is the properties a component receives.
Once the React Elements for all components are established , React converts it into actual HTML DOM elements.
Nesting in JSX
Additionally, nesting can be done in JSX just as it can be done in HTML. One key concern when nesting JSX nodes is to ensure that there always has to be a parent node.
Consider a bad JSX implementation:
const pageContent =
<h1 className="h1title">JSX in a nutshell</h1>
<p>It's amazing how JSX works</p>
To address the error which will be generated by the code above we can wrap it with a div as shown below:
const pageContent =
<div className="page-content">
<h1 className="h1title">JSX in a nutshell</h1>
<p>It's amazing how JSX works</p>
</div>
We can also console pageContent
object and see what it contains.
{
type: 'div',
props: {
children: [
{
type: 'h1',
props: {
className: 'h1title',
children: 'JSX in a nutshell'
}
},
{
type: 'p',
props: {
children: 'It\'s amazing how JSX works'
}
},
]
className: 'page-content',
}
}
children
is an array of two objects each representing a specific JSX node. Thid array will grow depending on the number of children a parent node has.
The ability of React to convert these objects into HTML elements without us, programmers, to implicitly do it, make React declarative.
Conclusion
Many React developers, myself included, lack an understanding of JSX and its role in React. However, after reading this article, we gained a straightforward understanding of JSX and how it enhances React as a powerful library.
If you enjoyed reading this article, please leave a like!
Top comments (4)
JSX is a strange melange...
JSX stands for Javascript XML, but it is generally used to embed HTML into JS. If I understand it right, we can assume, the precompiler converts any closed HTML tag to an JS-object, right? So the following definition should be ok:
But, can we use "a" in React to do anything useful with it? As far as I found, the possibilities are fairly limited.
Remember each object has some important attributes that should not miss. For example
The JS object has to have the attributes that was defined by react for it to work I presume.
You can use React without JSX, and as React was created before JSX, this was common practice this time see here.
It is just hard for me to understand, what the JSX compiler precisely does. In any case, it has to compile the input to pure Javascript, right?
I found this example:
What precisely is returned from App? A string, an object, some JSON?
If you compile this to something like
Then this returns an JS-object, that contains some HTML that contains some JS that contains some JSON. Isn't this a bit confusing?
Little known fact: JSX isn't just a React construct. It's actually used for a large number of other things, but they've definitely managed to convince the search engines that JSX == React