1. What is JSX?
JSX stands for JavaScript XML. It's a syntax extension for JavaScript that allows you to write HTML-like code directly within your JavaScript files. In Module 1, you've already written your first line of JSX:
const element = <h1>Hello, World!</h1>;
This might look like a string or HTML, but it's neither. Under the hood, Babel compiles this JSX into a standard JavaScript object. The line above becomes:
const element = React.createElement('h1', null, 'Hello, World!');
Writing `React.createElement` for every single element would be tedious. JSX is simply "syntactic sugar" that makes the code easier to write and read.
2. Using JavaScript inside JSX
The real power of JSX comes from its ability to embed any valid JavaScript expression directly inside it. You do this by wrapping the expression in curly braces `{}`.
For example, you can do math, access variables, or call functions right inside your JSX:
const name = "Sarah";
const element = <h1>Hello, {name}!</h1>;
// Renders: Hello, Sarah!
const a = 5;
const b = 10;
const element2 = <p>Total: {a + b}</p>;
// Renders: Total: 15
3. Specifying Attributes
JSX uses attributes just like HTML to describe elements. However, there are a few important differences because JSX is closer to JavaScript than HTML.
- Attributes are written in camelCase. For example, the HTML `class` attribute becomes `className` in JSX. This is because `class` is a reserved keyword in JavaScript. Similarly, `tabindex` becomes `tabIndex`.
- String values are specified with quotes, just like in HTML.
- JavaScript expressions can be used as attribute values by wrapping them in curly braces `{}`.
Here's an example that combines these rules:
const user = {
name: "John Doe",
avatarUrl: "https://i.pravatar.cc/150"
};
const element = (
<div className="profile">
<h2>{user.name}</h2>
<img src={user.avatarUrl} alt="User avatar" />
</div>
);