Why React, and Your First Components
React builds user interfaces from components: small, reusable functions that return markup. Instead of manually changing the DOM, you describe what the UI should look like for the current data, and React updates the page when the data changes. It assumes you know the JavaScript Fundamentals track.
Create a project
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev
Vite gives you a fast dev server with instant reloads.
A component
// src/components/ProjectCard.jsx
export function ProjectCard({ title, description, tags }) {
return (
<article className="card">
<h3>{title}</h3>
<p>{description}</p>
<ul className="tags">
{tags.map(tag => <li key={tag}>{tag}</li>)}
</ul>
</article>
);
}
// src/App.jsx
import { ProjectCard } from "./components/ProjectCard";
const projects = [
{ id: 1, title: "Booking app", description: "Salon appointments", tags: ["flask", "stripe"] },
{ id: 2, title: "Dashboard", description: "Sales analytics", tags: ["react", "charts"] },
];
export default function App() {
return (
<main>
<h1>Projects</h1>
{projects.map(p => <ProjectCard key={p.id} {...p} />)}
</main>
);
}
JSX rules
- JSX looks like HTML but is JavaScript:
classNameinstead ofclass,htmlForinstead offor, camelCase events (onClick). { }embeds any JavaScript expression.- A component returns one root element (use
<>...</>fragments to group). - Lists need a stable, unique
key(an ID, not the array index) so React can track items.
Props
Props are a component's inputs, passed like attributes. They are read-only: a component never changes its own props.
Conditional rendering
{isLoading ? <Spinner /> : <ProjectList items={items} />}
{error && <p className="error">{error}</p>}
Security note
React escapes text in { } automatically, so user content cannot inject HTML. The escape hatch dangerouslySetInnerHTML is named that way for a reason: only use it with sanitised content.
Exercise
Build a PricingCard component (name, price, features list, highlighted flag) and render four plans from an array, highlighting one.
Check yourself
- Why does each list item need a
key? - Can a component change its own props?
- Why is React output safe from XSS by default?
你的进度只保存在此浏览器中。
提交审核(10 积分)