JSX and Rendering UI
What Is JSX?
JSX (JavaScript XML) is a syntax extension for JavaScript that looks similar to HTML. It allows developers to write UI structures directly inside JavaScript code. React uses JSX to describe how the user interface should look.
For example:
const element = <h1>Hello, React!</h1>;
Behind the scenes, JSX is converted into standard JavaScript function calls. JSX makes code more readable and easier to understand when building UI components.
Embedding JavaScript in JSX
JSX allows you to use JavaScript expressions inside curly braces {}.
const name = "Alex";
function Welcome() {
return <h1>Hello, {name}!</h1>;
}
You can also perform calculations or combine values:
function App() {
const user = { firstName: "Sarah", lastName: "Lee" };
return <h2>{user.firstName + " " + user.lastName}</h2>;
}
Returning Multiple Elements
React components must return a single root element.
Incorrect:
return (
<h1>Title</h1>
<p>Description</p>
);
Correct using a wrapper element:
return (
<div>
<h1>Title</h1>
<p>Description</p>
</div>
);
Using a Fragment:
return (
<>
<h1>Title</h1>
<p>Description</p>
</>
);
Rendering Lists in JSX
You can render lists using the map() function.
const languages = ["JavaScript", "Python", "C#"];
function LanguageList() {
return (
<ul>
{languages.map((lang, index) => (
<li key={index}>{lang}</li>
))}
</ul>
);
}
Keys help React identify which items changed, were added, or removed.
Conditional Rendering
You can display elements conditionally using JavaScript logic.
Using ternary operator:
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h2>Welcome back!</h2> : <h2>Please sign in.</h2>}
</div>
);
}
Using logical AND (&&):
function Notifications({ count }) {
return (
<div>
{count > 0 && <p>You have {count} new notifications.</p>}
</div>
);
}
Styling in JSX
Inline styling example:
function Box() {
const boxStyle = { color: "white", backgroundColor: "blue", padding: "10px" };
return <div style={boxStyle}>Styled Box</div>;
}
Using CSS classes:
function Button() {
return <button className="primary-btn">Click Me</button>;
}
How React Renders UI
React converts JSX into a Virtual DOM representation. When state or props change, React compares the updated Virtual DOM with the previous version and updates only the changed elements in the real DOM. This efficient update process improves performance and user experience.
Summary
In this chapter, you learned what JSX is and how it helps build user interfaces in React. You saw how to embed JavaScript inside JSX, render multiple elements, create lists, apply conditional rendering, and style components. You also understood how React uses JSX and the Virtual DOM to render UI efficiently.