Props & PropTypes
Props are the primary way components talk to each other in React. They carry data from a parent to a child — like arguments to a function. In this chapter you'll master everything about props: how to pass every data type, how to validate them with PropTypes, set default values, use the special children prop, understand prop drilling and when it becomes a problem, and follow the best practices that make components truly reusable.
1. What are Props?
Props (short for properties) are the mechanism React uses to pass data from a parent component down to a child component. You can think of them exactly like function arguments — you pass them in when you use the component, and the component receives them to produce its output.
Props flow in one direction only — downward from parent to child. A child component cannot modify its own props. This predictable one-way flow is what makes React apps easy to reason about and debug.
useState).
2. Passing & Receiving Props
You pass props to a component the same way you write HTML attributes. React collects all the attributes, bundles them into a single object, and passes that object as the first argument to your component function.
// ── CHILD: define what props it accepts ──────────────────────
function ProductCard({ name, price, inStock }) {
return (
<div className="card">
<h2>{name}</h2>
<p>₹{price.toLocaleString()}</p>
<span>{inStock ? 'In Stock ✅' : 'Out of Stock ❌'}</span>
</div>
);
}
// ── PARENT: pass props like HTML attributes ───────────────────
function App() {
return (
<div>
<ProductCard
name="Wireless Headphones" {/* string — no curly braces needed */}
price={4999} {/* number — use { } */}
inStock={true} {/* boolean — use { } */}
/>
<ProductCard
name="USB-C Cable"
price={299}
inStock={false}
/>
</div>
);
}
name="Priya", age={25}, active.
{'{ name:"Priya", age:25, active:true }'}.{'{ name, age }'}.{'{name}'}, {'{age}'}. Any valid JS expression works.3. Passing Every Data Type as a Prop
Props can carry any JavaScript value. The syntax rule is simple:
strings use quotes; everything else
(numbers, booleans, arrays, objects, functions, JSX) goes inside
{'{ }'}.
function App() {
const handleClick = () => alert('Clicked!');
const tags = ['react', 'javascript', 'frontend'];
const user = { id: 1, name: 'Priya', city: 'Vadodara' };
return (
<Demo
title="Hello World" {/* string — quotes */}
count={42} {/* number — { } */}
isActive={true} {/* boolean — { } */}
isActive {/* boolean shorthand — same as ={true} */}
tags={tags} {/* array — { } */}
user={user} {/* object — { } */}
onClick={handleClick} {/* function — { } */}
icon={<span>⭐</span>} {/* JSX element — { } */}
/>
);
}
| Data Type | Syntax on Tag | Access in Child | Note |
|---|---|---|---|
| string | name="Priya"
|
{'{name}'}
|
Only type that doesn't need { } |
| number | age={'{25}'}
|
{'{age}'}
|
age="25"
would pass a string! |
| boolean | active={'{true}'}
or just active |
{'{active}'}
|
Attribute alone = true |
| array | items={'{list}'}
|
{'{items.map(...)}'}
|
Pass a variable, not inline array literal |
| object | user={'{userObj}'}
|
{'{user.name}'}
|
Spread with {'...user'} to
pass each key |
| function | onClick={'{handleClick}'}
|
{'{onClick()}'}
|
How children communicate back up |
| JSX / ReactNode | icon={'{
|
{'{icon}'}
|
Lets parent inject UI into child |
{'const p = { name:"Priya", age:25 };'}{' '} →
same as {' '}Useful when passing all props from a parent down to a child unchanged.
4. The Special children Prop
Every component automatically receives a special prop called children.
It contains whatever JSX you place between the component's opening and closing
tags.
This is how you build wrapper, layout, and slot-based components.
// ── REUSABLE CARD WRAPPER ─────────────────────────────────────
function Card({ title, children }) {
return (
<div className="card">
<h3 className="card-title">{title}</h3>
<div className="card-body">
{children} {/* ← renders whatever is placed inside <Card>...</Card> */}
</div>
</div>
);
}
// ── USAGE: nest anything between open/close tags ───────────────
function App() {
return (
<>
{/* Card 1 — children is a paragraph */}
<Card title="About Me">
<p>React developer from Vadodara.</p>
</Card>
{/* Card 2 — children is a whole form */}
<Card title="Login">
<input type="email" placeholder="Email" />
<button>Sign In</button>
</Card>
</>
);
}
children lets you separate structure (the
card border, title bar, padding)
from content (what goes inside). The parent decides what content to show;
the wrapper component only cares about how to display it.
This is React's version of the "slot" pattern you find in Vue and Web Components.
5. Default Prop Values
When a parent doesn't pass a prop, its value is undefined.
To avoid errors and keep components self-contained, always define
default values for props that have sensible fallbacks.
The modern approach is to use destructuring defaults directly in the parameter.
function Avatar({ name, size }) { return ( <div style={{ width: size, height: size }} > {name[0]} {/* ❌ crashes if name is undefined */} </div> ); }
function Avatar({ name = 'Guest', size = '48px', color = '#61dafb', }) { return ( <div style={{ width: size, height: size, background: color }} > {name[0]} {/* ✅ 'G' if no name passed */} </div> ); }
function Button({
label = 'Click Me', // string default
variant = 'primary', // string default
disabled = false, // boolean default
size = 'md', // string default
onClick = () => {}, // no-op function default — safe to call
}) {
return (
<button
className={`btn btn-${variant} btn-${size}`}
disabled={disabled}
onClick={onClick}
>
{label}
</button>
);
}
// Uses ALL defaults — renders a blue "Click Me" button
<Button />
// Overrides only label and variant
<Button label="Submit Form" variant="success" />
6. PropTypes — Runtime Prop Validation
PropTypes is a library that validates the types of props at runtime in development mode. If a parent passes the wrong type or forgets a required prop, React prints a clear warning in the browser console. It doesn't crash the app — it just warns you so you can fix it early.
$ npm install prop-types
import PropTypes from 'prop-types';
function UserCard({ name, age, email, role, tags, onFollow }) {
return (
<div>
<h2>{name}</h2>
<p>{age} yrs · {role}</p>
<p>{email}</p>
<div>{tags.map(t => <span key={t}>#{t}</span>)}</div>
<button onClick={onFollow}>Follow</button>
</div>
);
}
// Attach propTypes to the component function
UserCard.propTypes = {
name: PropTypes.string.isRequired, // must be string, required
age: PropTypes.number, // number, optional
email: PropTypes.string.isRequired, // required string
role: PropTypes.oneOf(['admin', 'user', 'guest']), // one of fixed values
tags: PropTypes.arrayOf(PropTypes.string), // array of strings
onFollow: PropTypes.func, // function, optional
};
Here are all the PropTypes validators you'll use regularly:
true or falseProductCard.propTypes = {
// shape — validates the structure of an object
product: PropTypes.shape({
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
image: PropTypes.string,
}).isRequired,
// arrayOf — validates each item in the array
reviews: PropTypes.arrayOf(
PropTypes.shape({
author: PropTypes.string,
rating: PropTypes.number,
comment: PropTypes.string,
})
),
// oneOf — restricts to specific string values (enum-like)
size: PropTypes.oneOf(['sm', 'md', 'lg']),
// oneOfType — accepts multiple types
id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
// func — callback prop
onAddToCart: PropTypes.func.isRequired,
};
7. Prop Drilling — What It Is & Why It Hurts
Prop drilling happens when you need to pass data through several layers of components that don't actually use the data themselves — they just pass it along to a deeper child. The middle components become "pass-through" pipes.
// ❌ PROP DRILLING — Page and Section don't use "user", just pass it on
function App() {
const user = { name: 'Priya', role: 'admin' };
return <Page user={user} />;
}
function Page({ user }) { // doesn't use user — just drills it
return <Section user={user} />;
}
function Section({ user }) { // doesn't use user — just drills it
return <UserBadge user={user} />;
}
function UserBadge({ user }) { // finally uses user here
return <span>{user.name} — {user.role}</span>;
}
8. Props Best Practices
onFollow not handleFollowClick. isLoading not loading (boolean props start with is/has/can).props.name = 'new' or props.list.push(...). Create new values instead.
Mutation breaks React's rendering model.name is used, pass
only name. Fewer props = smaller API = easier to
reuse.Explore More Tutorials
The correct pattern depends on where the data is needed:
Option 1 — Callback prop: The parent passes a function as a prop (e.g.
onNameChange). When the child needs to trigger a change, it calls that
function. The parent updates its own state, which flows back down as new props.
Option 2 — Lift state up: Move the state to the nearest common ancestor of the components that need it, and pass it down as props.
Option 3 — Context / Redux: For deeply shared state, use the Context API or a state management library.
PropTypes.node — anything that React can render: strings,
numbers, booleans, arrays, fragments, and React elements. Very broad — use for the
children prop when content can be anything.
PropTypes.element — specifically a single React
element (the result of JSX, e.g. <Icon />). More restrictive
— use when you expect exactly one component to be passed.
Practical rule: If you're typing the
children prop, use
PropTypes.node. If you're typing a slot prop like icon or
header that should be a single component, use
PropTypes.element.
Signs you have prop drilling:
• A prop appears in a component's parameter list but is never rendered or used in logic — only passed to a child
• Changing one prop requires updating 3+ files
• A "middle" component's tests break when you rename a prop it doesn't use
1–2 levels of passing is normal. When it reaches 3+ levels, consider React Context or a state manager.
onClick and the default is undefined,
then calling onClick() inside the component throws:
TypeError: onClick is not a function
By setting the default to
() => {'{}'} (an empty no-op function), you
can always safely call onClick() — it just does nothing if the parent
didn't provide a real handler. This avoids defensive if (onClick) onClick()
checks everywhere in your component.
<Button count="5" />. What type is count inside the Button component?props.children contain
when you write <Card><p>Hello</p></Card>?
- Props are read-only data passed from parent to child — like arguments to a function. They flow in one direction only: downward.
- Strings use quotes on the tag; everything else (numbers, booleans, arrays, objects,
functions, JSX) uses
{'{ }'}. - A boolean prop with no value (e.g.
active) is shorthand foractive={'{true}'}. - The
childrenprop holds JSX placed between a component's opening and closing tags — great for wrapper/layout components. - Default values are set via destructuring defaults in the function parameter
— the modern replacement for
defaultProps. - PropTypes validates prop types at runtime in development. Install with
npm install prop-types. Set.isRequiredfor mandatory props. - Key validators:
string,number,bool,func,node,element,arrayOf,shape,oneOf. - Prop drilling (3+ levels of unused pass-through) is a sign to use Context API or a state manager. 1–2 levels of passing is normal and fine.
- Best practices: descriptive names, never mutate props, minimal interface, always validate, provide sensible defaults, use callback props for child-to-parent communication.
<ProductCard />
with PropTypes validation that accepts product
(shape), onBuy
(func) and children.
Render 3 instances in App.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.