Props and Children
Components often need to share data. You can pass data from a parent component down to a child component using props (short for properties).
Props are read-only. A child component must never modify its own props directly.
Passing Props
Props look exactly like HTML attributes when you pass them to a component.
// App.jsx
import UserCard from './UserCard.jsx';
export default function App() {
return (
<div className="layout">
{/* Passing strings and numbers as props */}
<UserCard name="Alice" age={25} />
<UserCard name="Bob" age={30} />
</div>
);
}
Receiving Props
React bundles all the props passed to a component into a single JavaScript object. The standard practice is to use object destructuring directly inside the function parameters to extract the values.
// UserCard.jsx
export default function UserCard({ name, age }) {
return (
<div className="card">
<h2>Name: {name}</h2>
<p>Age: {age}</p>
</div>
);
}
The children Prop
There is a special prop reserved by React called children. It allows you to pass nested JSX elements directly inside a component, much like a standard HTML <div> wraps other elements.
// Layout.jsx
export default function Layout({ children }) {
return (
<main className="container mx-auto">
<nav>Navigation Bar</nav>
{/* Content renders here */}
<div className="content">
{children}
</div>
<footer>Footer</footer>
</main>
);
}
You use the layout by passing content between the opening and closing tags.
// App.jsx
import Layout from './Layout.jsx';
export default function App() {
return (
<Layout>
<h1>Page Title</h1>
<p>This paragraph is passed as the children prop!</p>
</Layout>
);
}