Components & Props
Building UIs from reusable functions - how components compose, how props pass data down, and the children prop pattern.
What it is, in plain English: A component is a JavaScript function that returns JSX describing a piece of UI. Props (short for properties) are how data flows into a component — they work like function parameters, passed from a parent component to a child. Props are read-only from the child's perspective: a component never modifies its own props. Composing many small components together is the core technique for building complex UIs.
Functions that return UI, and the data passed into them
A basic component
function Greeting() {
return <h1>Hello!</h1>;
}
// Use it like an HTML tag:
function App() {
return (
<div>
<Greeting />
<Greeting /> {/* reusable — use it as many times as you want */}
</div>
);
}Props — passing data into a component
// Props are like function arguments, but passed as an object:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return (
<div>
<Greeting name="Alice" /> {/* props = { name: "Alice" } */}
<Greeting name="Bob" /> {/* props = { name: "Bob" } */}
</div>
);
}Destructuring props (the common style)
// Instead of props.name, props.age — destructure directly in the function signature:
function UserCard({ name, age, role }) {
return (
<div>
<h2>{name}</h2>
<p>{age} years old, {role}</p>
</div>
);
}
// Usage:
<UserCard name="Alice" age={30} role="Engineer" />
{/* Note: {30} not "30" — curly braces pass it as a number, not string */}Default prop values
function Button({ label, variant = "primary" }) {
// If variant isn't passed, it defaults to "primary"
return <button className={`btn-${variant}`}>{label}</button>;
}
<Button label="Save" /> {/* uses default: variant="primary" */}
<Button label="Delete" variant="danger" /> {/* overrides default */}Props are read-only
function Counter({ initialCount }) {
// ✗ NEVER modify props directly:
// initialCount = initialCount + 1; // wrong! props are read-only
// ✓ If you need to change a value over time, use state instead (next page):
const [count, setCount] = React.useState(initialCount);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
Try It Yourself (JSX)
Official Sources
- React Documentation — Your First Component
- React Documentation — Passing Props to a Component
- React Documentation — Passing JSX as children
The Codex links only to official documentation. No third-party tutorials.