JSX Syntax and Rendering Elements
JSX is a syntax extension for JavaScript that looks like HTML. Under the hood, JSX compile tools convert this syntax into standard JavaScript function calls.
1. Key Rules of JSX
To write valid JSX, you must follow these syntax rules:
- Single Root Element: A component must return a single root element. If you do not want to add extra DOM wrapper divs, use a React Fragment (empty tags).
- Closing Tags: All tags must be explicitly closed (for example, self-closing tags like img or input must end with a slash).
- CamelCase Properties: HTML attributes are replaced by camelCase names in JSX. For example, use
classNameinstead ofclass, andtabIndexinstead oftabindex. - Embedding JavaScript: You can embed any valid JavaScript expressions inside JSX by wrapping them in curly braces.
Example of JSX rules:
// Valid JSX syntax
function Profile() {
const userName = "Bob";
return (
<>
<h1 className="title">User Profile</h1>
<p>Name: {userName.toUpperCase()}</p>
<img src="avatar.png" alt="Profile avatar" />
</>
);
}2. Component Props (Properties)
Props are read-only properties passed from a parent component to configure a child. They behave like HTML attributes:
// Parent Component passing props
function App() {
return (
<div>
<Greeting name="Alice" age={25} />
</div>
);
}
// Child Component receiving props
function Greeting(props) {
return (
<p>Hello, my name is {props.name} and I am {props.age} years old.</p>
);
}3. Conditional Rendering
You can control what elements are rendered based on state or props using standard JavaScript logical operators:
Using Ternary Operator
function AuthButton({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <button>Log Out</button> : <button>Log In</button>}
</div>
);
}Using Logical AND (&&)
Use this when you want an element to render only if a condition is true:
function Dashboard({ hasNotifications }) {
return (
<div>
<h1>User Panel</h1>
{hasNotifications && <span className="badge">New Alert!</span>}
</div>
);
}4. List Rendering and Keys
When rendering lists of elements, use the JavaScript map method. You must assign a unique key prop to each list element so React can track additions and moves efficiently:
function ItemList() {
const products = [
{ id: 101, name: "Keyboard" },
{ id: 102, name: "Mouse" },
{ id: 103, name: "Monitor" }
];
return (
<ul>
{products.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}Published on Last updated: