- React Tutorial
- React Home
- React Setup
- React Introduction
- React ES6
- React Render HTML
- React JSX
- React Components
- React Class
- React Props
- React Events
- React Conditional
- React Lists
- React Forms
- React Router
- React Memo
- React CSS Styling
- React Hooks
- What is a Hook?
- React useState
- React useEffect
- React useContext
- React useRef
- React useReducer
- React useCallback
- React useMemo
- React Custom Hooks
React JSX
In the realm of React, JSX, or JavaScript XML, is a powerful syntax extension. It provides a familiar and concise way to describe exactly what the UI should look like. While it might look like HTML, JSX is actually a syntax sugar that sits on top of JavaScript, allowing you to write your components with a structure that is both visual and easy to maintain.
JSX isn't required to use React, but it has become the industry standard because it allows developers to see the UI structure directly within their logic, bridging the gap between design and functionality.
React.createElement() calls) so the browser can understand and execute it.
Coding in JSX
In the early days of React, or if you choose not to use JSX, creating even a simple element involved using the React.createElement() method. As your application grows and you start nesting elements (like a div containing a ul with multiple li tags), this method becomes incredibly difficult to read and manage.
Let's contrast the traditional approach with the modern JSX approach:
// Traditional way with React.createElement()
// This gets messy very quickly as nesting increases
const elem = React.createElement('h1', { className: 'greeting' }, 'Hello World!');
And the modern, more direct approach using JSX:
// Using JSX
// It looks like HTML, making it intuitive for web developers
const elem = <h1 className="greeting">Hello World!</h1>;
This simplicity in syntax significantly enhances the readability of React components, allowing you to focus on the structure of your application rather than the boilerplate code required to create it.
class becomes className and onclick becomes onClick.
Expressions in JSX
One of the key features of JSX is the ability to embed JavaScript expressions directly within your markup using curly braces {}. Think of these braces as a "portal" that lets you jump back into standard JavaScript logic while inside your UI structure.
{}, it’s usually better to move that logic into a variable or a function outside the return statement to keep your component clean.
Mathematical Operations
You can perform any valid mathematical calculation directly inside your JSX. This is useful for things like calculating prices, percentages, or dynamic dates.
// Example: Calculating years or dynamic values
const elem1 = <h1>React was released in {2010 + 3}</h1>;
// Real-world example: Simple shopping cart total
const price = 19.99;
const tax = 1.08;
const totalElem = <p>Total including tax: ${(price * tax).toFixed(2)}</p>;
Variables/States
The most common use of expressions is injecting data from variables or component states into the UI. This is how you create dynamic views that update when your data changes.
const name = "rJ";
const role = "Developer";
// Concatenating variables within JSX
const elem3 = <h1>{name} is a {role}</h1>;
<div>{userObject}</div> will throw an error. You must access specific properties, like <div>{userObject.name}</div>.
Ternary Operators
Since if-else statements don't work inside JSX (because JSX expects an expression that returns a value), we use ternary operators for conditional rendering. This is perfect for toggling UI elements based on a user's status.
const isLoggedIn = true;
// If true, show "Welcome back!", if false, show "Please log in"
const userGreeting = <h1>{isLoggedIn ? "Welcome back!" : "Please log in"}</h1>;
// Real-world: Displaying a "Loading..." spinner or the content
const isLoading = false;
const content = <div>{isLoading ? <Spinner /> : <MainContent />}</div>;
Mapping Arrays
In React, you'll frequently need to display a list of items from an array. We use the .map() method for this because it transforms each item in your data array into a JSX element, returning a new array of elements that React knows how to render.
const fruits = ['Apple', 'Banana', 'Orange'];
const elem5 = (
<ul>
{fruits.map((fruit, index) => (
/* Each list item needs a unique "key" prop for React's performance */
<li key={index}>{fruit}</li>
))}
</ul>
);
key prop when mapping through an array. This helps React identify which items have changed, been added, or been removed, which is vital for performance and preventing UI bugs.
Embracing expressions in JSX allows for the seamless integration of variables, states, and logic, making your React code both expressive and highly functional.