
ReactJS
Props validation helps you catch mistakes before they become bugs. You specify what type each prop should be, and React warns you in development if someone passes the wrong type.
When props have the wrong type, components can fail silently or behave unexpectedly. Validation catches these mistakes early, making development easier and your code more reliable:
function UserCard({ name, age }) {
return (
<div>
<h2>{name}</h2>
<p>Age: {age + 5}</p> {/* Bug if age is a string: "28" + 5 = "285" */}
</div>
);
}
// Passing string instead of number - hard to notice
<UserCard name="John" age="28" />Validation catches this mistake immediately.
<details>
<summary>📚 More Examples</summary>
// Without validation - hard to debug
function List({ items }) {
return items.map(item => <li>{item}</li>); // Crashes if items is a string!
}
<List items="apple" /> // Should be array, but no warning
// With validation - clear error
List.propTypes = {
items: PropTypes.array.isRequired,
};
<List items="apple" /> // React warns immediately in development</details>
Import the PropTypes library and add a `propTypes` object to your component. This object defines what each prop should be:
import PropTypes from 'prop-types';
function Button({ text, color = "blue", size = "medium" }) {
return <button style={{ background: color }}>{text}</button>;
}
Button.propTypes = {
text: PropTypes.string.isRequired, // Must be string, must be provided
color: PropTypes.string, // Should be string, optional
size: PropTypes.oneOf(['small', 'medium', 'large']), // One of these values
};When someone passes the wrong type, React shows a warning in the browser console during development. These warnings don't affect production.
<details>
<summary>📚 More Examples</summary>
import PropTypes from 'prop-types';
function UserProfile({ username, age, email, onLogout }) {
return (
<div>
<h2>{username}</h2>
<p>Age: {age}</p>
<button onClick={onLogout}>Logout</button>
</div>
);
}
UserProfile.propTypes = {
username: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
email: PropTypes.string.isRequired,
onLogout: PropTypes.func.isRequired, // Function prop
};</details>
| Type | Accepts | Example |
|---|---|---|
| `string` | Text | `"Hello"` |
| `number` | Numbers | `42` or `3.14` |
| `bool` | true/false | `true` |
| `array` | Arrays | `[1, 2, 3]` |
| `object` | Objects | `{ id: 1 }` |
| `func` | Functions | `() => {}` |
| `node` | Anything renderable | Text, JSX, elements |
| `.isRequired` | Must be provided | `PropTypes.string.isRequired` |
| `oneOf([...])` | Specific values only | `oneOf(['small', 'large'])` |
Ready to practice? Challenges | Next: Props vs State
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward