पाठ 4 / 25
Components and Props
Inputs flow down.
Functions with read-only inputs
A component is a function whose name starts with a capital letter and that returns JSX. Parents pass data to children through props, an object of named values (strings, numbers, objects, functions, other elements). Props are read-only: a component must not modify them. Destructuring with defaults ({ label, tone = "info" }) documents what a component accepts. Data flows down through props; to send information up, parents pass callback functions as props.
Build UI from small pieces
Components take props, compose through children, and render lists and conditions.
Rendering components with props to HTML, run
I ran this with React 19.3 and react-dom 19.3 on Node.js 22, compiling JSX with esbuild 0.28. Browser-style examples use jsdom 29 as a fake DOM (imported from a small setup-dom.mjs file) and act() to apply updates. Profile passes a user object down and renders two Badge components; the second Badge uses the default tone "info" and receives children. renderToStaticMarkup shows the HTML React produces.
import { renderToStaticMarkup } from "react-dom/server";
function Badge({ label, tone = "info", children }) {
return <span className={`badge badge-${tone}`}>{label}{children && <small> {children}</small>}</span>;
}
function Profile({ user }) {
return (
<div className="profile">
<h2>{user.name}</h2>
<Badge label="Admin" tone="warning" />
<Badge label="Joined">{user.joined}</Badge>
</div>
);
}
console.log(renderToStaticMarkup(<Profile user={{ name: "Asha", joined: "2024" }} />));
Output:
<div class="profile"><h2>Asha</h2><span class="badge badge-warning">Admin</span><span class="badge badge-info">Joined<small> 2024</small></span></div>
Keep components small and named
If a component does several unrelated jobs or its JSX scrolls off the screen, split it into named sub-components.
त्वरित जाँच: Can a child component change the props it receives?
- Yes, freely
- No, props are read-only; change state in the owner instead
- Only strings can be changed
- Only on the server
Answer
No, props are read-only; change state in the owner instead — Data flows down; events flow up.