Components & JSX
Components are the building blocks of every React app. JSX is how you write what they display.
What is a component?
A component is a JavaScript function that returns some UI. Its name must start with a capital letter so React can tell it apart from ordinary HTML tags.
function Welcome() {
return <p>Welcome to my site!</p>;
}
Once you have defined a component, you can use it inside other components, just like an HTML element:
function App() {
return (
<div>
<h1>My Site</h1>
<Welcome />
<Welcome />
</div>
);
}
Combining components this way is called composition. A whole application is a tree of components nested inside one another.
JSX
JSX looks like HTML, but it lives inside JavaScript. A build tool converts it into ordinary JavaScript function calls before it reaches the browser. There are a few rules to know:
1. Return a single root element
If you need to return several elements, wrap them in a parent element or in an empty fragment (<>...</>):
return (
<>
<h2>Title</h2>
<p>Some text</p>
</>
);
2. Close every tag
Self-closing tags need a slash: <img />, <br />, <input />.
3. Use camelCase attributes
Most attributes use camelCase, and class becomes className because class is a reserved word in JavaScript:
<button className="primary" onClick={handleClick}>
Save
</button>
4. Use curly braces for JavaScript
Anything inside { } is evaluated as a JavaScript expression:
const user = { name: "Ada", avatar: "/ada.png" };
return (
<div>
<img src={user.avatar} alt={user.name} />
<p>{user.name} has {2 + 3} new messages.</p>
</div>
);
Props: passing data to components
Props (short for properties) let a parent component pass data to a child, in the same way attributes configure an HTML element. The child receives them as a single object, usually destructured:
function Avatar({ name, size = 64 }) {
return (
<img
src={`/images/${name}.png`}
alt={name}
width={size}
height={size}
/>
);
}
function Profile() {
return (
<div>
<Avatar name="ada" size={100} />
<Avatar name="grace" />
</div>
);
}
Props are read-only. A component should never change its own props. To change something over time, use state.
The children prop
Whatever you put between a component's opening and closing tags arrives as children. This makes layout components such as cards and panels easy to write:
function Card({ children }) {
return <div className="card">{children}</div>;
}
<Card>
<h3>Hello</h3>
<p>This goes inside the card.</p>
</Card>
Conditions and lists
Because JSX is JavaScript, you use ordinary JavaScript to show things conditionally or to repeat them.
function TodoList({ todos, isLoggedIn }) {
if (!isLoggedIn) {
return <p>Please log in.</p>;
}
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
{todo.text} {todo.done && "✔"}
</li>
))}
</ul>
);
}
When rendering a list, give each item a unique key prop. React uses keys to track which items were added, removed or reordered.