Skip to content

ReactJS - JSX

React utilizes JSX (JavaScript XML) as a syntax extension for JavaScript, allowing you to write HTML-like structures within your JavaScript code. While you can use React without JSX, it’s a common and recommended practice due to several benefits:

  • JSX can be more readable and expressive, especially for developers familiar with HTML, as it visually represents the UI structure.
  • Many build tools optimize JSX compilation, potentially leading to performance benefits.
  • JSX helps in catching errors earlier, often during the compilation step if syntax is incorrect.

JSX elements look very similar to HTML tags. Here’s a basic example within a functional component:

import React from 'react';
function App() {
return (
<div>
Hello World!!!
</div>
);
}
export default App;

While JSX resembles HTML, there are key differences and rules to keep in mind.

A React component’s render method (for class components) or return statement (for functional components) must return a single root element. If you want to return multiple elements, wrap them in a single parent tag like a <div>, or use a React.Fragment (or its shorthand <></>) to avoid adding an extra node to the DOM.

import React from 'react';
function App() {
return (
<React.Fragment>
<h1>Header</h1>
<h2>Content</h2>
<p>This is the content!!!</p>
</React.Fragment>
// Or using shorthand syntax:
// <>
// <h1>Header</h1>
// <h2>Content</h2>
// <p>This is the content!!!</p>
// <>
);
}
export default App;

The output will show a header, a sub-header, and a paragraph, all rendered as sibling elements in the DOM if using Fragments, or nested within a div if a div wrapper is used.

JSX uses camelCase for most HTML attribute names. For example, class becomes className and for becomes htmlFor. This is because JSX is closer to JavaScript than HTML, and class and for are reserved keywords in JavaScript. You can also use standard HTML attributes and custom data attributes (prefixed with data-).

import React from 'react';
function App() {
return (
<div>
<h1 className="main-title">Header</h1>
<h2>Content</h2>
<p data-custom-attribute="somevalue">This is the content!!!</p>
<label htmlFor="username">Username:</label>
<input type="text" id="username" />
</div>
);
}
export default App;

You can embed any valid JavaScript expression within JSX by wrapping it in curly braces {}. For instance, to display the result of an arithmetic operation:

import React from 'react';
function App() {
const result = 1 + 1;
return (
<div>
<h1>{result}</h1> {/* Displays 2 */}
<p>User: {'John Doe'.toUpperCase()}</p> {/* Displays User: JOHN DOE */}
</div>
);
}
export default App;

The output for the first example will be an <h1> tag containing the number 2.

Standard if-else statements cannot be used directly inside JSX. However, you can use conditional (ternary) expressions or logical && operators for conditional rendering.

import React from 'react';
function App() {
const isLoggedIn = true;
let count = 5;
return (
<div>
<h1>{isLoggedIn ? 'Welcome Back!' : 'Please Log In'}</h1>
{count > 0 && <p>You have {count} new messages.</p>}
</div>
);
}
export default App;

In this example, ‘Welcome Back!’ will be rendered. If isLoggedIn were false, ‘Please Log In’ would appear. If count is greater than 0, the message about new messages will be displayed.

React allows using inline styles. When applying inline styles, you pass a JavaScript object to the style attribute. Property names are camelCased (e.g., fontSize instead of font-size). React automatically appends px to certain numeric inline style properties. While inline styles are convenient for dynamic styling or simple cases, for larger applications, consider CSS Modules, CSS-in-JS libraries (like Styled Components or Emotion), or utility-first CSS frameworks (like Tailwind CSS) for better maintainability and scalability. For more information, refer to [Link to React Docs on Styling and CSS].

import React from 'react';
function App() {
const myStyle = {
fontSize: '32px', // Explicitly setting px, or use a number for React to infer for some properties
color: '#FF0000',
backgroundColor: 'lightyellow' // camelCase for background-color
};
return (
<div>
<h1 style={myStyle}>Header with Inline Styles</h1>
</div>
);
}
export default App;

The header text will be rendered with a font size of 32px, red color, and a light yellow background.

To write comments within JSX, you need to wrap them in curly braces {} and then use JavaScript comment syntax (/* ... */).

import React from 'react';
function App() {
return (
<div>
<h1>Header</h1>
{/* This is a single-line comment in JSX */}
{/*
This is a
multi-line comment
in JSX
*/}
<p>Some content.</p>
</div>
);
}
export default App;

Standard HTML elements are written in lowercase (e.g., <div>, <p>). React components, whether class-based or functional, must start with an uppercase letter (e.g., <MyComponent />, <UserProfile />). This distinction is crucial for JSX to differentiate between HTML tags and React components.

Remember to use className instead of class for CSS classes, and htmlFor instead of for in label elements. These are important distinctions due to JSX being JavaScript.

As stated on the React official documentation:

Since JSX is JavaScript, identifiers such as class and for are discouraged as XML attribute names. Instead, React DOM components expect DOM property names like className and htmlFor, respectively.