Default Values for Props in React JS
Topic: Default Values for Props
Course: React JS Training
1. Introduction to Default Values for Props
In React JS, props are used to pass data from a parent component to a child component. Sometimes, a parent component may not provide a value for every prop. In such situations, default values allow a component to use a predefined value when a prop is missing or undefined.
Default values make components more reliable, reusable, and easier to maintain. They are especially useful when a component has optional information, such as a user's name, a product description, a button label, or a theme color.
Example
function Greeting({ name = "Guest" }) {
return <h2>Welcome, {name}!</h2>;
}
function App() {
return (
<div>
<Greeting name="Rahul" />
<Greeting />
</div>
);
}
export default App;
Output:
Welcome, Rahul!
Welcome, Guest!
In this example, the first Greeting component receives the name "Rahul". The second Greeting component does not receive a name prop, so it uses the default value "Guest".
2. What Are Default Props?
Default props are fallback values used when a component does not receive a particular prop value. In modern functional components, default values are commonly defined using JavaScript parameter destructuring.
For example, a Button component may use "Click Me" as its default label when the parent does not provide a label.
Example
function Button({ label = "Click Me" }) {
return <button>{label}</button>;
}
function App() {
return (
<div>
<Button label="Submit" />
<Button />
</div>
);
}
export default App;
The first button displays "Submit", while the second displays "Click Me".
3. Why Are Default Values for Props Important?
- Prevent missing information: Components can display meaningful fallback content when optional props are not supplied.
- Improve reusability: Components can work even when a parent provides only some of their props.
- Improve readability: Default values make a component's expected behavior clearer.
- Reduce repetitive code: Parents do not need to provide the same fallback value every time.
- Support consistent interfaces: Buttons, cards, profiles, and other components can use standard labels or styles.
- Simplify component usage: Developers can provide only the props that need to differ from the defaults.
4. Setting Default Values with Destructuring
The simplest modern approach is to assign a default value while destructuring props in the function parameter.
Syntax
function ComponentName({ propName = defaultValue }) {
return <p>{propName}</p>;
}
Example
function Student({ name = "Unknown Student" }) {
return <h2>Student Name: {name}</h2>;
}
function App() {
return (
<div>
<Student name="Priya" />
<Student />
</div>
);
}
export default App;
Output:
Student Name: Priya
Student Name: Unknown Student
The default is used only when name is missing or its value is undefined. If the parent provides a valid name, that value is used instead.
5. Default Values for Multiple Props
A component can define default values for multiple props. This is useful when the component accepts several optional values.
Example
function UserProfile({
name = "Guest",
city = "Not Provided",
role = "Visitor"
}) {
return (
<div>
<h2>{name}</h2>
<p>City: {city}</p>
<p>Role: {role}</p>
</div>
);
}
function App() {
return (
<div>
<UserProfile name="Rahul" city="Mumbai" role="Student" />
<UserProfile name="Priya" />
<UserProfile />
</div>
);
}
export default App;
In this example, any omitted prop uses its own default value. Priya's profile uses the default city and role, while the final profile uses all three defaults.
6. Default Values for String Props
String props contain text, such as names, titles, descriptions, labels, and messages. A default string is useful when a text value is optional.
Example
function Course({ title = "Course Title Not Available" }) {
return <h2>{title}</h2>;
}
function App() {
return (
<div>
<Course title="React JS Training" />
<Course />
</div>
);
}
export default App;
The second Course component displays "Course Title Not Available" because no title prop was supplied.
7. Default Values for Number Props
Number props are used for values such as age, quantity, price, marks, and ratings. A default number can be assigned if the parent does not provide one.
Example
function Student({ marks = 0 }) {
return <p>Marks: {marks}</p>;
}
function App() {
return (
<div>
<Student marks={85} />
<Student />
</div>
);
}
export default App;
Output:
Marks: 85
Marks: 0
The default value is the number 0, not the string "0". Use curly braces when passing numeric values in JSX.
8. Default Values for Boolean Props
Boolean props represent true or false conditions. They can control whether a feature is enabled, whether a message is displayed, or whether a component is in a particular state.
Example
function Notification({ isVisible = true }) {
return (
<div>
{isVisible ? <p>You have a new notification.</p> : null}
</div>
);
}
function App() {
return (
<div>
<Notification />
<Notification isVisible={false} />
</div>
);
}
export default App;
The first Notification uses the default value true and displays the message. The second explicitly passes false, so it does not display the message.
9. Default Values for Array Props
Array props are useful for lists of items, such as skills, categories, products, or navigation links. A default empty array allows a component to work when no list is provided.
Example
function Skills({ skills = [] }) {
return (
<div>
<h2>Skills</h2>
{skills.length > 0 ? (
<ul>
{skills.map((skill) => (
<li key={skill}>{skill}</li>
))}
</ul>
) : (
<p>No skills added yet.</p>
)}
</div>
);
}
function App() {
return (
<div>
<Skills skills={["HTML", "CSS", "React"]} />
<Skills />
</div>
);
}
export default App;
The first Skills component displays a list. The second uses the default empty array and displays a fallback message.
10. Default Values for Object Props
When a component receives an object prop, you can provide a default object if the entire prop is missing or undefined.
Example
const defaultUser = {
name: "Guest",
city: "Unknown"
};
function UserCard({ user = defaultUser }) {
return (
<div>
<h2>{user.name}</h2>
<p>City: {user.city}</p>
</div>
);
}
function App() {
const userData = {
name: "Amit",
city: "Pune"
};
return (
<div>
<UserCard user={userData} />
<UserCard />
</div>
);
}
export default App;
The second UserCard uses defaultUser because the user prop is not supplied. If an object is supplied but one of its properties is missing, the default object does not automatically fill in that missing property. You can define property-level defaults separately if needed.
11. Default Values for Nested Object Properties
Sometimes an object is provided but one or more of its properties are missing. You can use destructuring inside the component to assign defaults to individual properties.
Example
function Employee({ employee = {} }) {
const {
name = "Unknown Employee",
department = "Not Assigned"
} = employee;
return (
<div>
<h2>{name}</h2>
<p>Department: {department}</p>
</div>
);
}
function App() {
return (
<div>
<Employee employee={{ name: "Priya" }} />
<Employee />
</div>
);
}
export default App;
In the first Employee component, the name is Priya and the department uses its default. In the second component, both properties use their defaults.
12. Default Values for Function Props
Function props allow a parent to provide a function that a child component can call. A default no-operation function can be used when a callback is optional and the component should safely do nothing if it is not provided.
Example
function ActionButton({ onAction = () => {}, label = "Click Me" }) {
return (
<button onClick={onAction}>
{label}
</button>
);
}
function App() {
return (
<div>
<ActionButton label="No Action Set" />
<ActionButton
label="Show Message"
onAction={() => alert("Button clicked!")}
/>
</div>
);
}
export default App;
The first button safely does nothing because its callback was not supplied. The second button runs the function provided by its parent. Use a no-operation callback only when doing nothing is an appropriate fallback; for required actions, it may be better to require the callback.
13. Difference Between Missing, Undefined, Null, and Empty String
Understanding these values is important because JavaScript default values do not treat them all the same way.
| Value passed |
Example |
Does destructuring default apply? |
| Prop missing |
<Greeting /> |
Yes |
| Undefined |
name={undefined} |
Yes |
| Null |
name={null} |
No |
| Empty string |
name="" |
No |
| Valid value |
name="Rahul" |
No; the supplied value is used |
Example
function Greeting({ name = "Guest" }) {
return <p>Hello, {String(name)}!</p>;
}
function App() {
return (
<div>
<Greeting />
<Greeting name={undefined} />
<Greeting name={null} />
<Greeting name="" />
<Greeting name="Rahul" />
</div>
);
}
export default App;
This example demonstrates that the default is used for a missing or undefined prop, but not for null or an empty string.
14. Default Values Using Logical OR
In JavaScript, the logical OR operator (||) can provide a fallback value when an expression is falsy. However, it behaves differently from a destructuring default.
Example
function Greeting(props) {
const name = props.name || "Guest";
return <h2>Hello, {name}!</h2>;
}
This code uses "Guest" when name is an empty string, 0, false, null, or undefined. That may not always be what you want.
15. Default Values Using the Nullish Coalescing Operator
The nullish coalescing operator (??) uses a fallback only when a value is null or undefined. It preserves values such as an empty string, false, and zero.
Example
function Score(props) {
const marks = props.marks ?? 0;
return <p>Marks: {marks}</p>;
}
function App() {
return (
<div>
<Score marks={80} />
<Score marks={0} />
<Score marks={null} />
<Score />
</div>
);
}
export default App;
The nullish coalescing operator is useful when zero or false are valid values that should not be replaced by a fallback.
16. Default Values in Functional Components vs Class Components
Functional components commonly define defaults through parameter destructuring. Class components may use a static defaultProps property.
Functional Component
function Greeting({ name = "Guest" }) {
return <h2>Hello, {name}!</h2>;
}
Class Component
import { Component } from "react";
class Greeting extends Component {
render() {
return <h2>Hello, {this.props.name}!</h2>;
}
}
Greeting.defaultProps = {
name: "Guest"
};
export default Greeting;
For modern functional components, parameter defaults are a clear and straightforward approach. Class components may still be encountered in existing applications, where defaultProps is a familiar pattern.
17. Default Values and the defaultProps Property
Historically, React components have used a defaultProps property to define fallback values. For example, class components can continue to use this pattern. For function components, prefer JavaScript parameter defaults in modern code rather than relying on defaultProps.
Example for a Class Component
class Button extends React.Component {
render() {
return <button>{this.props.label}</button>;
}
}
Button.defaultProps = {
label: "Click Me"
};
The default label is used when the label prop is omitted or undefined. Remember to import React if you use React.Component, or import Component directly from React.
18. Default Values and Conditional Rendering
Default values can be combined with conditional rendering to make a component behave sensibly when optional information is not supplied.
Example
function Profile({ name = "Guest", isPremium = false }) {
return (
<div>
<h2>{name}</h2>
{isPremium ? (
<p>Premium Member</p>
) : (
<p>Standard Member</p>
)}
</div>
);
}
function App() {
return (
<div>
<Profile name="Rahul" isPremium={true} />
<Profile />
</div>
);
}
export default App;
The first profile displays Rahul as a Premium Member. The second displays Guest as a Standard Member using the default values.
19. Default Values in Reusable Components
Default values make reusable components easier to use because callers only need to provide the values that differ from the defaults.
Example: Reusable Button
function Button({
label = "Click Me",
color = "blue",
type = "button"
}) {
return (
<button
type={type}
style={{
backgroundColor: color,
color: "white",
padding: "10px 16px",
border: "none",
borderRadius: "5px"
}}
>
{label}
</button>
);
}
function App() {
return (
<div>
<Button />
<Button label="Save" color="green" />
<Button label="Delete" color="red" />
</div>
);
}
export default App;
The first button uses all defaults. The other buttons override the label and color while keeping the default type.
20. Common Mistakes When Using Default Values
- Expecting defaults to replace null: Destructuring defaults apply to missing or undefined values, not null.
- Using the wrong prop name: A default cannot correct a mismatch between the name passed by the parent and the name read by the child.
- Confusing strings and numbers: Use curly braces when passing JavaScript numbers and boolean expressions.
- Assuming object properties are filled automatically: A default object is used when the whole prop is undefined, but it does not fill missing fields in an object that was supplied.
- Using logical OR without considering zero or false: The
|| operator treats these values as falsy and may replace them unexpectedly.
- Adding unnecessary defaults: Do not hide missing required information with a misleading fallback.
- Mutating default data: Treat props and shared objects as read-only. Avoid modifying a shared default object.
- Using a no-operation callback for a required action: If an event handler must exist, make it required or provide an intentional fallback.
21. Best Practices for Default Values
- Use parameter destructuring to define defaults for functional component props.
- Choose clear, meaningful fallback values.
- Use defaults for optional props, not to conceal missing required data.
- Understand the difference between undefined, null, empty strings, false, and zero.
- Use
?? when a fallback should apply only to null or undefined.
- Use
|| only when all falsy values should trigger the fallback.
- Provide sensible defaults for labels, themes, optional lists, and other nonessential values.
- For objects and arrays, avoid mutating values received through props.
- Keep prop names and component interfaces consistent.
- Use TypeScript or another validation approach when the project needs stricter prop contracts.
22. Practical Project: Student Profile Cards
In this project, you will build a reusable StudentCard component with default values for name, course, age, and city.
Step 1: Create StudentCard.jsx
function StudentCard({
name = "Unknown Student",
course = "Course Not Assigned",
age = "Not Provided",
city = "Unknown City"
}) {
return (
<div className="student-card">
<h2>{name}</h2>
<p>Course: {course}</p>
<p>Age: {age}</p>
<p>City: {city}</p>
</div>
);
}
export default StudentCard;
Step 2: Use StudentCard in App.jsx
import StudentCard from "./StudentCard";
function App() {
return (
<div>
<h1>Student Profiles</h1>
<StudentCard
name="Rahul Sharma"
course="React JS"
age={22}
city="Mumbai"
/>
<StudentCard
name="Priya Patel"
course="Web Development"
age={21}
/>
<StudentCard />
</div>
);
}
export default App;
Step 3: Add Styling in App.css
.student-card {
max-width: 320px;
padding: 16px;
margin: 12px 0;
border: 1px solid #cccccc;
border-radius: 8px;
background-color: #f8f9fa;
}
.student-card h2 {
margin-top: 0;
color: #1d4ed8;
}
.student-card p {
font-size: 16px;
}
Project Explanation
- The first StudentCard receives all four values from App.
- The second StudentCard receives name, course, and age, so city uses its default value.
- The third StudentCard receives no props and uses all four defaults.
- The same component renders each profile without repeating the component's markup.
23. Interview Questions and Answers
Q1. What are default values for props in React?
Answer: They are fallback values used when a prop is missing or undefined.
Q2. How do you set default values in a functional component?
Answer: Use parameter destructuring, such as function Greeting({ name = "Guest" }).
Q3. Do default values apply when a prop is null?
Answer: No. JavaScript destructuring defaults apply when the value is undefined, not when it is null.
Q4. Can a component have multiple default props?
Answer: Yes. You can assign defaults to multiple properties in the same destructured parameter.
Q5. What is the difference between a default value and a value passed by a parent?
Answer: A supplied value is used when provided. The default is used only when the prop is missing or undefined.
Q6. How can you provide a default for an array prop?
Answer: Use a default empty array, for example function Skills({ skills = [] }).
Q7. How do you provide a fallback for null or undefined?
Answer: Use the nullish coalescing operator, such as const value = props.value ?? "Default", when that behavior is appropriate.
Q8. What is the difference between || and ???
Answer: || uses the fallback for any falsy value, including zero, false, and an empty string. ?? uses the fallback only for null or undefined.
Q9. Can class components have default props?
Answer: Yes. Class components can define a static defaultProps property or assign a defaultProps object to the class.
Q10. Why are default values useful?
Answer: They improve component reusability, provide sensible fallback content, reduce repetitive code, and make optional props easier to handle.
24. Practice Exercises
- Create a Greeting component with a default name of "Guest".
- Create a Product component with default name, price, and category values.
- Create a Button component with default label, color, and type props.
- Create a Student component with default age and course values.
- Create a Skills component that uses an empty array when no skills are supplied.
- Create a Notification component whose visibility defaults to true.
- Create a UserProfile component that uses a default object when the user prop is missing.
- Test how destructuring defaults behave when a prop is missing, undefined, null, or an empty string.
- Write an example showing the difference between the logical OR and nullish coalescing operators.
- Complete the Student Profile Cards project and test all default values.
25. Quick Revision Checklist
- Understand what default values for props are.
- Know how to set defaults with parameter destructuring.
- Set defaults for strings, numbers, booleans, arrays, objects, and functions.
- Understand that defaults apply to missing or undefined values.
- Remember that null and empty strings do not trigger destructuring defaults.
- Know the difference between
|| and ??.
- Understand default values in functional and class components.
- Recognize common mistakes and follow best practices.
- Build the Student Profile Cards project.
- Practice the interview questions and exercises.
26. Conclusion
Default values for props help React components work correctly when optional values are not provided. In modern functional components, JavaScript parameter destructuring is a simple and readable way to set defaults. Understanding the behavior of undefined, null, empty strings, zero, and false will help you choose the correct fallback technique.
By practicing default values with strings, numbers, booleans, arrays, objects, and reusable components, you can create more flexible and maintainable React JS applications.
27. React JS Training Resources
Explore the course details and register for a demo using the following links:
28. Official React Documentation
Learn more about passing props and setting defaults in the official React documentation: Passing Props to a Component – React Documentation.