Understanding JSX: Importance and Benefits Explained


In transitioning from vanilla JavaScript to React, one of the first things you'll encounter is JSX. JSX is simply a syntax extension that allows you to write HTML-like code directly within JavaScript, making it easier to build React components. While it might feel a bit overwhelming at first, it's something worth understanding. In this article, we'll walk through the basics of JSX and why it's so important in React development.
What is JSX
JavaScript XML is a syntax extension that enables writing of HTML-like code within JavaScript files possible. That is, rather than the traditional approach of separating markup and logic, JSX brings them together, making it easier to visualise and build user interfaces. Consider the code block below
const element = <h1> Hello, this is my first react project </h1>
As you can see, the element
is a JS variable, which holds what looks like an HTML tag. However, it’s not directly HTML. For this reason, it is often said HTML + JS = JSX.
How JSX Works Behind the Scenes
It is important to note that the only language that web browsers understand is JavaScript. Hence, for JSX to be functional, it is first transpiled into React.createElement()
calls, which ultimately return a plain JS object.
For instance, assuming you type this in your editor,
const element = <p> Hello, I am using React </p>;
The code will be formatted to
const element = React.createElement('p', null, 'Hello, I am using React');
//which conforms to
const element = React.createElement(type, props, ...children)
For efficient rendering, React uses a virtual Document Object Model (DOM), which is a lightweight copy of the actual DOM. When changes occur in the code editor, React updates the virtual DOM first and then compares this updated virtual DOM with the previous version. Based on the differences found, React applies only the necessary updates to the real DOM, making the UI faster and more efficient.
Why Use JSX
JSX is used in React for several key reasons, including:
Providing the all-in-one-structure
A major reason to use JSX in React is that it provides a seamless way of blending markup, styling, and logic into one body, making the process of UI development less cumbersome. Instead of switching between separate HTML, CSS, and JavaScript files to build a component, JSX allows you to manage all three in one place. This promotes a more organised structure, especially as your application grows. It also makes components more readable and easier to maintain since everything related to that component can be found in a single location.
Ability to Re-use Components
The use of JSX in React makes it possible to create components which can be imported, exported, or referenced to build larger applications. A component can be reused in multiple parts of your project without rewriting the code. This saves development time and keeps your codebase cleaner. JSX supports this reusability by allowing you to write components in a readable, modular format, making it easy to manage and scale even as the application grows in complexity.
Improved Code Structure
When code is written in JSX format, it is easier to read and understand because it resembles the foundational structure of HTML and JavaScript, which most developers are already familiar with. This familiar layout means you don't have to spend time decoding unusual syntax just to figure out what's going on. JSX allows you to fully comprehend the structure of your UI and how the data flows within it. This clarity not only improves individual productivity but also makes it easier for teams to collaborate, especially when onboarding new developers to a project.
Can JS be Written in JSX?
Yes. It is possible to write JS in a JSX file through embedding. Embedding involves using curly braces to wrap the JS code to return data dynamically, as it would in a regular JS file.
Consider the example below.
//code block showing a greeting to a user
const name = 'John';
const userGreeting = <p>Hello {name}, welcome to our company</p>
export default function Intro() {
return(
<>
{userGreeting}
</>
)
//The Intro component is then rendered on the Root Component
The output on the browser would be
Hello John, welcome to our company.
Another use case of embedding is
//code block showing the embedding of student scores
const testScore = 27;
const examScore = 49;
export default function ScoreChecker() {
return(
<>
<p>Your total score is {testScore + examScore}</p>
</>
)
}
//The ScoreChecker component is then rendered on the Root Component
The outcome on the browser is
Your total score is 76
Other Basic JSX Rules
The Top-level Element Requirement
There is an existing rule that requires all JSX code to be wrapped in a top-level element or a single element to be valid. Therefore, anything typed outside this root element will be flagged as an error. Most commonly, divs
and other semantic tags can be used as the parent element, as seen below.
//the use of div as the top level element
export default function ProfileCard() {
return (
<div>
<img src="https://image_ID.com/" alt="User Avatar" />
<h2>Robert Tom</h2>
<p>Frontend Developer</p>
</div>
);
}
In other cases, empty opening and closing tags called Fragments are used.
//the use of fragments
export default function ProfileCard() {
return (
<>
<img src="https://image_ID.com/" alt="User Avatar" />
<h2>Robert Tom</h2>
<p>Frontend Developer</p>
</>
);
}
CSS ClassName
Over time, in regular HTML and CSS, the keyword class
has been used to define CSS class names. However, when writing JSX in a React file, this changes slightly. Instead of using class
, JSX requires the use of className
to assign CSS classes. This adjustment is necessary because class
is a reserved keyword in JavaScript, and JSX is essentially some sort of JavaScript.
This is how defining a class is done in HTML.
in<!-- index.html -->
<div class="Intro">
<h1 class="title">Welcome to My Website</h1>
</div>
However, the className is a must-use in JSX as seen below
// App.jsx
function App() {
return (
<div className="Intro">
<h1 className="title">Welcome to My Website</h1>
</div>
);
}
The Self-closing syntax
In HTML, self-closing tags like <img>
, <br>
, and <hr>
could be written without using the closing slash (/>
). On the contrary, the closing slash is mandatory when writing JSX because the omission of this will result in a syntax error. Consider the code block below, where the closing slash in the img
element is removed.
//code block showing an img element without the closing slash
export default function ImgElement() {
return (
<>
<img src="https://image.com/" alt="User Avatar">
</>
);
}
The error message, as displayed in the browser is
No Traditional if-else Statements
The use of traditional if-else statements is not directly supported in JSX; rather, other powerful tools like the Ternary Operator and Short-circuit evaluation of logical operators have become quick decision-making approaches, especially in conditional rendering.
// Ternary operator usage for decision making and conditional Rendering
const isUserSubscribed = false;
export default function SubscriptionStatusChecker() {
return (
<>
{isUserSubscribed? (<h1>Thank you for subscribing!</h1>) : (<h2>Not subscribed. Kindly subscribe for more content.</h2>)}
</>
);
}
In the above example, since isUserSubscribed
is false, the second element (h2
) content is rendered to the browser. Similarly, this is also possible using logical operators, as seen below.
//conditional rendering using logical operators
const isUserSubscribed = false;
export default function SubscriptionStatusChecker() {
return (
<>
{isUserSubscribed && <h1>Thank you for subscribing!</h1>}
{!isUserSubscribed && <h2>Not subscribed. Kindly subscribe for more content.</h2>}
</>
);
}
Conclusion
JSX plays a vital role in React code by bringing together HTML, CSS, and JavaScript into a single, cohesive structure that makes building dynamic user interfaces much easier. By understanding how JSX works, you’ll be better equipped to write clear, efficient code and avoid the common pitfalls many developers face early on. Take your time to absorb the concepts shared in this article, as they’ll serve as a strong foundation as you grow in your React journey.
Subscribe to my newsletter
Read articles from EKOT, BUKMFONABASI ANIETIE directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
