React: interfaces with components
React is a library for building interfaces. The core idea: the UI is split into reusable components. In modern React, a component is simply a function that returns what should be painted.
function Welcome() {
return <h1>Hello, React!</h1>;
}
- The component name is capitalized (
Welcome, notwelcome). - It returns JSX: a syntax that looks like HTML but lives inside JavaScript.
JSX
JSX lets you write markup inside JS. Between curly braces { } you can embed
JavaScript expressions:
function Greeting() {
const name = "Ann";
return <h1>Hello, {name}</h1>;
}
Key JSX rules:
- It must return a single root element. If you need several, wrap them in a
<div>(or in a fragment<>...</>). - Attributes are written in camelCase:
className(notclass),onClick. - Tags without a closing tag are self-closing:
<img />,<br />.
function Card() {
return (
<div className="card">
<h2>Title</h2>
<p>Content</p>
</div>
);
}
In these exercises you write the component and see it rendered in the preview instantly.