Accessing Props in React
Course: React JS Training
Topic: Accessing Props in React
Learning Objectives: Understand how to access props in functional and class components, use dot notation and destructuring, access nested objects and arrays, handle default values, use the children prop, and follow best practices when working with props.
1. Introduction to Accessing Props
Props stands for Properties. In React, props are used to pass data from a parent component to a child component. Accessing props means reading and using the values received by a component to display dynamic content or control its rendering.
For example, a parent component can pass a student's name to a child component. The child can access the name and display it on the screen.
Example
function Student(props) {
return <h2>Student Name: {props.name}</h2>;
}
function App() {
return <Student name="Rahul" />;
}
export default App;
Output:
Student Name: Rahul
Explanation: The App component passes the name prop. The Student component accesses it using props.name.
2. Understanding the Props Object
In a functional component, React provides the component's props as its first argument. This argument is an object containing the values passed through JSX attributes.
Example
function Employee(props) {
return (
<div>
<h2>{props.name}</h2>
<p>Department: {props.department}</p>
<p>Experience: {props.experience} years</p>
</div>
);
}
function App() {
return (
<Employee
name="Priya"
department="IT"
experience={3}
/>
);
}
export default App;
Explanation: React passes the three properties in one props object. The child accesses them using props.name, props.department, and props.experience.
3. Accessing Props Using Dot Notation
Dot notation is a simple way to access individual properties from the props object. Write props. followed by the property name.
Syntax
props.propertyName
Example
function Product(props) {
return (
<div>
<h2>Product: {props.name}</h2>
<p>Price: ₹{props.price}</p>
<p>Category: {props.category}</p>
</div>
);
}
function App() {
return (
<Product
name="Laptop"
price={55000}
category="Electronics"
/>
);
}
export default App;
Output:
Product: Laptop
Price: ₹55000
Category: Electronics
When to use it: Dot notation is useful when you want to keep the complete props object available or when learning how props work.
4. Accessing Props Using Destructuring
JavaScript object destructuring allows you to extract properties from an object into individual variables. In React, it is commonly used to access props more concisely.
Syntax
function Component({ propName }) {
return <p>{propName}</p>;
}
Example
function Student({ name, course, city }) {
return (
<div>
<h2>Name: {name}</h2>
<p>Course: {course}</p>
<p>City: {city}</p>
</div>
);
}
function App() {
return (
<Student
name="Amit"
course="React JS"
city="Mumbai"
/>
);
}
export default App;
Explanation: The values name, course, and city are extracted from the props object and can be used directly in the component.
Dot Notation vs. Destructuring
| Dot Notation |
Destructuring |
function User(props) |
function User({ name }) |
Access with props.name |
Access with name |
| Keeps the props object available |
Extracts selected properties |
| Useful when several properties are accessed dynamically |
Often more concise for common component code |
Both approaches are correct. Choose the one that makes your component easiest to read.
5. Accessing String Props
String props are commonly used for names, titles, messages, descriptions, and labels.
Example
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
function App() {
return (
<div>
<Greeting name="Neha" />
<Greeting name="Rohit" />
</div>
);
}
export default App;
Output:
Hello, Neha!
Hello, Rohit!
The same component can display different values based on the string prop it receives.
6. Accessing Number and Boolean Props
Props can also contain numbers and Boolean values. Numbers are commonly used for prices, ages, and quantities. Booleans are useful for conditions such as availability or login status.
Example: Number Props
function ProductPrice({ price }) {
return <p>Price: ₹{price}</p>;
}
function App() {
return <ProductPrice price={1200} />;
}
Example: Boolean Props
function Availability({ isAvailable }) {
return (
<p>
{isAvailable ? "Available" : "Out of Stock"}
</p>
);
}
function App() {
return (
<div>
<Availability isAvailable={true} />
<Availability isAvailable={false} />
</div>
);
}
Explanation: The component reads the Boolean value and uses a conditional expression to display the appropriate message.
7. Accessing Props Containing Objects
An object prop groups related information together. After accessing the object prop, you can use dot notation to read its individual properties.
Example
function UserProfile({ user }) {
return (
<div>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>City: {user.address.city}</p>
</div>
);
}
function App() {
const userData = {
name: "Aarav Sharma",
email: "[email protected]",
address: {
city: "Pune"
}
};
return <UserProfile user={userData} />;
}
export default App;
Explanation:
user accesses the object passed by the parent.
user.name retrieves the user's name.
user.email retrieves the email address.
user.address.city retrieves a value from a nested object.
Important: Make sure nested properties exist before accessing them. If a nested value might be missing, optional chaining such as user.address?.city can help avoid errors.
8. Accessing Array Props
Array props are useful when a component needs to display multiple items, such as courses, products, tasks, or student records.
Example
function CourseList({ courses }) {
return (
<ul>
{courses.map((course) => (
<li key={course.id}>{course.name}</li>
))}
</ul>
);
}
function App() {
const courses = [
{ id: 1, name: "React JS" },
{ id: 2, name: "JavaScript" },
{ id: 3, name: "HTML and CSS" }
];
return <CourseList courses={courses} />;
}
export default App;
Explanation: The component receives the array through courses. It accesses each item with map() and displays the course name.
Note: Use stable, unique keys for rendered list items. In this example, each course has an id.
9. Accessing Props with Default Values
A default value provides a fallback when a prop is missing or has the value undefined. You can set a default directly in the destructured function parameter.
Example
function Welcome({ name = "Guest" }) {
return <h2>Welcome, {name}!</h2>;
}
function App() {
return (
<div>
<Welcome name="Riya" />
<Welcome />
</div>
);
}
export default App;
Output:
Welcome, Riya!
Welcome, Guest!
Important: The default is used for a missing prop or undefined, but not for null, false, or 0.
10. Accessing the Children Prop
The special children prop contains the content placed between a component's opening and closing JSX tags. It is often used to create reusable cards, panels, and layout components.
Example
function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}
function App() {
return (
<Card>
<h2>React JS</h2>
<p>Learn React component fundamentals.</p>
</Card>
);
}
export default App;
Explanation: The heading and paragraph are passed to Card as its children prop. The component renders that nested content inside its wrapper.
11. Accessing Function Props
Props can contain functions. A child component can access a callback prop and call it in response to an event, such as a button click.
Example
function ActionButton({ onAction }) {
return (
<button onClick={onAction}>
Perform Action
</button>
);
}
function App() {
function handleAction() {
alert("Action completed!");
}
return <ActionButton onAction={handleAction} />;
}
export default App;
Explanation: The parent passes the function as onAction. The child accesses it through destructuring and uses it as the button's click handler.
Pass the function reference as onAction={handleAction}, rather than calling it immediately with onAction={handleAction()}.
12. Accessing Props in Class Components
Although functional components are generally recommended for new React code, class components are still supported. In a class component, props are accessed through this.props.
Example
import { Component } from "react";
class Student extends Component {
render() {
return (
<div>
<h2>Name: {this.props.name}</h2>
<p>Course: {this.props.course}</p>
</div>
);
}
}
export default function App() {
return (
<Student name="Amit" course="React JS" />
);
}
Explanation: The Student class component reads the incoming props with this.props.name and this.props.course.
Remember: Functional components use their function parameter to access props, while class components use this.props.
13. Accessing Props vs. Accessing State
Props and state can both affect the UI, but they have different purposes.
| Feature |
Props |
State |
| Meaning |
Inputs supplied to a component |
Data managed by a component |
| Access in a function component |
Through the props parameter or destructuring |
Through a state variable returned by a Hook such as useState |
| Access in a class component |
this.props |
this.state |
| How values change |
The parent supplies updated props |
The owning component updates state using the appropriate setter or method |
| Typical examples |
Product name, user details, button callback |
Counter value, form input, menu visibility |
14. Props Are Read-Only
Props should be treated as read-only snapshots. A component should not directly change the props object or mutate objects and arrays received through props.
Incorrect Example
function User({ user }) {
user.name = "Updated Name";
return <h2>{user.name}</h2>;
}
Problem: This code mutates an object received through props. Such mutations can lead to inconsistent rendering and difficult-to-debug behaviour.
Better Example
function User({ user }) {
const displayName = user.name;
return <h2>{displayName}</h2>;
}
If information needs to change, update the state that owns the data or pass new values from the parent. Avoid mutating props directly.
15. Special Props: key and ref
Most JSX attributes become props that a component can access. However, React treats key and ref specially, so they are not ordinary props available through props.key or props.ref.
Example
function StudentRow({ id }) {
return <p>Student ID: {id}</p>;
}
function App() {
return <StudentRow key="student-1" id="student-1" />;
}
Explanation: React uses key to identify elements in lists. The child receives the separate id prop, which it can access normally.
For a component that needs an identifier in its own logic, pass that identifier as a regular prop in addition to key when needed.
16. Common Mistakes When Accessing Props
| Mistake |
Correct Practice |
Using props.name when the function only destructures name |
Use the variable name, or accept the complete props object. |
| Forgetting to pass a required prop |
Pass the value from the parent or provide a suitable default. |
| Accessing a missing nested property |
Validate the data or use optional chaining where appropriate. |
| Mutating props or nested objects |
Treat props as read-only and create new data when changes are needed. |
Trying to read props.key |
Pass a separate regular prop if the component needs the same identifier. |
| Calling a callback during rendering |
Pass the callback reference and call it when the relevant event occurs. |
| Forgetting keys when rendering arrays |
Use stable, unique keys for list elements. |
17. Best Practices for Accessing Props
- Use clear and descriptive prop names.
- Use destructuring when it makes the component easier to read.
- Use dot notation when working with the complete props object is convenient.
- Provide sensible defaults for optional values.
- Check that nested objects and arrays have the expected structure.
- Never modify props directly.
- Use callbacks passed through props for child-to-parent interaction.
- Remember that
key and ref are special React attributes, not ordinary props.
- Keep components focused on displaying or using the data they receive.
18. Practical Project: Employee Profile
Objective: Create a reusable employee profile component that accesses several props, including an object and an array.
App.jsx
function EmployeeProfile({ employee }) {
return (
<div className="employee-card">
<h2>{employee.name}</h2>
<p>Role: {employee.role}</p>
<p>City: {employee.city}</p>
<h3>Skills</h3>
<ul>
{employee.skills.map((skill) => (
<li key={skill}>{skill}</li>
))}
</ul>
</div>
);
}
export default function App() {
const employeeData = {
name: "Neha Sharma",
role: "Frontend Developer",
city: "Mumbai",
skills: ["HTML", "CSS", "JavaScript", "React"]
};
return <EmployeeProfile employee={employeeData} />;
}
Project Explanation
- The parent creates an employee object.
- The object is passed to the child through the
employee prop.
- The child accesses object values such as
employee.name and employee.role.
- The child uses
map() to display the skills array.
- The component can be reused for other employees by passing different objects.
19. Interview Questions and Answers
Q1. What does accessing props mean in React?
Answer: It means reading the values passed to a component by its parent and using them to render or configure the UI.
Q2. How do you access props in a functional component?
Answer: You can use the props object, such as props.name, or destructure properties in the function parameter, such as function User({ name }).
Q3. How do you access props in a class component?
Answer: Use this.props, for example this.props.name.
Q4. What is destructuring in React?
Answer: Destructuring is a JavaScript feature that extracts values from an object into variables. It provides a concise way to access props.
Q5. How do you access nested object props?
Answer: Use dot notation such as user.address.city, after ensuring the nested values exist.
Q6. How do you access an array passed as props?
Answer: Access the array through its prop name and use methods such as map() to render its items.
Q7. Can props be changed inside a component?
Answer: Props should be treated as read-only. The parent should supply updated values, often by updating its own state.
Q8. What is the children prop?
Answer: It contains content nested between a component's opening and closing tags.
Q9. Can a component access props.key?
Answer: No. React reserves key for its own element-handling purposes. Pass the identifier separately as a regular prop if the component needs it.
Q10. What happens when a parent passes new props?
Answer: React can render the child using the new prop values, updating the displayed output as needed.
20. Practice Exercises
- Create a
Student component and access name, age, and course props.
- Create a
ProductCard component that displays name, price, and availability.
- Access a nested city property from a user object.
- Pass an array of course names and render them using
map().
- Create a
Greeting component with a default name of "Guest".
- Create a card component that accesses and displays the
children prop.
- Build a button component that accesses a callback prop and runs it on click.
- Create an employee profile component using an object prop and an array of skills.
21. Quick Revision Checklist
- Props are inputs supplied to React components.
- Functional components receive props as their first argument.
- Props can be accessed using dot notation or destructuring.
- Class components access props using
this.props.
- Props can contain strings, numbers, Booleans, objects, arrays, functions, and JSX.
- Default values can be specified through parameter destructuring.
- The
children prop contains nested JSX content.
- Props must be treated as read-only.
key and ref are special React attributes rather than ordinary props.
- Updated props can lead to a new render with updated values.
22. Official Documentation and Course Links
Explore the official React documentation to learn more about accessing and using props:
JustAcademy React JS Training
23. Conclusion
Accessing props is an essential React skill. You can read props through dot notation or destructuring, access nested data, render arrays, use default values, and work with callback functions. By treating props as read-only inputs and choosing clear access patterns, you can build reusable, understandable, and maintainable React components.