Tutorials React JS Props & PropTypes
Ch 9 / 47
Chapter 9 Beginner 11 min read React JS

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.

Advertisement
What you'll learn
What props are — the one-way data flow mental model
Passing all data types — string, number, boolean, array, object, function
The children prop — building wrapper and layout components
Default prop values — graceful fallbacks with destructuring defaults
PropTypes validation — catching bugs at runtime in development
All PropTypes validators — string, number, shape, arrayOf, oneOf and more
Prop drilling — what it is, why it hurts, and how to recognise it
Props best practices — naming, immutability, single source of truth

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.

One-Way Data Flow — Props go Parent → Child
<App /> — root, owns all data
↓
name="Priya"   role="Developer"   city="Vadodara"
↓
<UserPage /> — receives props, passes some down
↓
name="Priya"   role="Developer"
↓
<UserCard /> — renders the UI from props
↓
label="Follow"
↓
<Button /> — leaf component, uses label prop
Data can only travel downward. A child can never push data back up through props.
Props are read-only — always A component must never modify its own props. Treat props as a snapshot of input at render time. If you need data to change in response to user interactions, that's what state is for (Chapter 12 — 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.

jsx — ProductCard.jsx — passing and receiving props
// ── 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>
  );
}
1
You write attributes
Write attributes on the JSX tag just like HTML: name="Priya", age={25}, active.
2
React bundles them
React collects all attributes into one object: {'{ name:"Priya", age:25, active:true }'}.
3
Function receives it
Your function is called with that object as the first argument. Destructure in the parameter for clean access: {'{ name, age }'}.
4
You use them in JSX
Access inside JSX with curly braces: {'{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 {'{ }'}.

jsx — passing every data type as a prop
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
Spread an object as props If you have an object whose keys match the component's props, you can spread it instead of listing each one:
{'const p = { name:"Priya", age:25 };'}
{''}  →  same as  {''}
Useful when passing all props from a parent down to a child unchanged.
Advertisement

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.

jsx — Card.jsx — using the children prop as a slot
// ── 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>
    </>
  );
}
Why children is powerful 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.

No defaults — crashes if prop missing
function Avatar({ name, size }) {
  return (
    <div
      style={{ width: size, height: size }}
    >
      {name[0]}  {/* ❌ crashes if name is undefined */}
    </div>
  );
}
With defaults ✅ — always safe
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>
  );
}
jsx — practical default values pattern
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.

bash — install prop-types
$ npm install prop-types
jsx — UserCard.jsx — PropTypes in practice
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:

PropTypes.string
Expects a JavaScript string value
name="Priya"
PropTypes.number
Expects a JavaScript number (int or float)
age={'{25}'}
PropTypes.bool
Expects true or false
active={'{true}'}
PropTypes.func
Expects a function reference
onClick={'{fn}'}
PropTypes.array
Expects any array (elements unchecked)
items={'{[]}'}
PropTypes.object
Expects any plain object (keys unchecked)
config={'{{}}'}
PropTypes.node
Anything renderable — string, number, element, array, fragment
children
PropTypes.element
A single React element (JSX tag)
icon={'{ }'}
PropTypes.arrayOf(type)
Array where every item matches a specific type
arrayOf(string)
PropTypes.shape({'{ }'})
Object with specific key/type structure
shape({'{name:string}'})
PropTypes.oneOf(['a','b'])
Must be one of a fixed list of values (like an enum)
oneOf(['sm','md','lg'])
PropTypes.oneOfType([…])
Accepts any one of multiple type validators
string or number
.isRequired
Append to any validator — warns if the prop is missing or undefined
string.isRequired
jsx — advanced PropTypes: shape, arrayOf, oneOf
ProductCard.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,
};
PropTypes vs TypeScript PropTypes works at runtime (in the browser, dev mode only). TypeScript works at compile time (in your editor, catches errors before you run the code). In modern projects, TypeScript is preferred over PropTypes because it catches errors earlier and gives better editor autocomplete. But PropTypes is still used in JavaScript-only React projects.
⭐⭐⭐⭐⭐
4.9 / 5
🔥 Most Popular at K2infocom · Vadodara
React JS Complete
Masterclass
Props, State, Hooks, Context, Router, Redux, REST APIs & 6 real-world projects — guided by experts with 100% placement support.
Props & State Hooks React Router Redux Toolkit REST APIs 6 Projects Certificate
2,500+Students
6+Projects
3–6Months
100%Placement

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.

jsx — prop drilling: passing user 3 levels deep
// ❌ 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>;
}
Problems with Prop Drilling
Middle components carry props they don't use, making them harder to understand. Any rename of a prop requires updating every layer. Components become tightly coupled.
Avoid when deep
When it's Acceptable
1–2 levels of passing is perfectly fine and actually preferred over global state. Prop drilling only becomes a problem when you're passing through 3+ levels unnecessarily.
1–2 levels OK
Solutions for Deep Drilling
Use React Context API (Chapter 19) to share data without passing through every level. For complex global state, use Redux (Chapter 30) or Zustand (Chapter 31).
Context / Redux

8. Props Best Practices

Use Descriptive Names
Prop names should describe what they are, not how they're used. onFollow not handleFollowClick. isLoading not loading (boolean props start with is/has/can).
Naming
Never Mutate Props
Treat every prop as frozen. Never do props.name = 'new' or props.list.push(...). Create new values instead. Mutation breaks React's rendering model.
Immutability
Minimal Props Interface
Pass only what the component actually needs. If you're spreading the entire user object when only name is used, pass only name. Fewer props = smaller API = easier to reuse.
Simplicity
Always Add PropTypes or TypeScript
Document what every component expects. PropTypes catches type errors at runtime in dev. TypeScript catches them at compile time. Either way, future you (and teammates) will thank you.
Validation
Provide Sensible Defaults
Every optional prop should have a default value. Components should work standalone, without the parent needing to know about every optional prop. Default functions as no-ops prevent null-call errors.
Robustness
Avoid Deep Prop Drilling
If a prop travels more than 2 levels without being used, consider lifting state or using Context. Keep props flowing naturally — components should only know about data they actually render or pass directly.
Architecture
Advertisement
Knowledge Check — Props & PropTypes
Q1. A child component wants to update data it received via props. What should it do?
A child component cannot and should not modify its own props — they are read-only.

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.
Q2. What is the difference between PropTypes.node and PropTypes.element?
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.
Q3. What is prop drilling and how do you recognise it?
Prop drilling is when data is passed from a component down through multiple intermediate components that do not use the data themselves — they just pass it to a deeper child.

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.
Q4. Why set a no-op arrow function as the default for a function prop?
If a parent doesn't pass 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.
Multiple Choice
MCQ 1
You write <Button count="5" />. What type is count inside the Button component?
MCQ 2
Which PropTypes validator would you use to ensure a prop is one of the strings "sm", "md", or "lg"?
MCQ 3
What does props.children contain when you write <Card><p>Hello</p></Card>?
MCQ 4
PropTypes validation runs in which environment?
Chapter 9 Summary — Props & PropTypes
  • 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 for active={'{true}'}.
  • The children prop 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 .isRequired for 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.
Practice — Build a Reusable Card Component
Create a <ProductCard /> with PropTypes validation that accepts product (shape), onBuy (func) and children. Render 3 instances in App.
Open Vite + React Sandbox

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel