Accessing Props in React JS
Topic: Accessing Props
Course: React JS Training
1. Introduction to Accessing Props
In React JS, props (short for properties) 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, control rendering, or customize the component's behavior.
For example, a parent component can pass a student's name, age, and course to a Student component. The Student component accesses those values and displays them on the screen.
Example
function Student(props) {
return (
<div>
<h2>Name: {props.name}</h2>
<p>Age: {props.age}</p>
<p>Course: {props.course}</p>
</div>
);
}
function App() {
return (
<Student
name="Rahul"
age={21}
course="React JS"
/>
);
}
export default App;
Output:
Name: Rahul
Age: 21
Course: React JS
Here, the Student component accesses the values through props.name, props.age, and props.course.
2. What Are Props?
Props are inputs provided to a React component. They allow a component to receive information from the component that renders it. Props can contain strings, numbers, booleans, arrays, objects, functions, and JSX elements.
Props are read-only from the receiving component's perspective. A component should use the values it receives rather than directly modifying them.
Example
function Welcome(props) {
return <h1>Welcome, {props.username}!</h1>;
}
function App() {
return <Welcome username="Manish" />;
}
export default App;
In this example, the parent passes the username prop, and the Welcome component reads it using props.username.
3. Why Is Accessing Props Important?
- Dynamic content: Display different information based on received values.
- Reusable components: Use the same component with different data.
- Parent-child communication: Read information supplied by a parent component.
- Conditional rendering: Display content based on a prop's value.
- Maintainability: Keep components flexible and avoid duplicating code.
- Customization: Control text, styling, status, and other component features through props.
4. Accessing Props Using the props Object
A functional component receives its props as an object parameter. You can access each property using dot notation.
Syntax
function ComponentName(props) {
return <p>{props.propertyName}</p>;
}
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 Sharma"
department="Development"
experience={3}
/>
);
}
export default App;
Explanation:
props.name accesses the employee's name.
props.department accesses the department.
props.experience accesses the number of years of experience.
This approach is useful when learning how React passes information to components.
5. Accessing Props Through Destructuring
Destructuring is a JavaScript feature that extracts properties from an object into separate variables. In React, it is commonly used to access props more concisely.
Example
function Student({ name, age, course }) {
return (
<div>
<h2>{name}</h2>
<p>Age: {age}</p>
<p>Course: {course}</p>
</div>
);
}
function App() {
return (
<Student
name="Amit"
age={22}
course="Web Development"
/>
);
}
export default App;
In this example, name, age, and course are extracted directly from the props object. Therefore, the component can use these names without writing props. repeatedly.
6. Accessing Individual Props
A component can access only the properties it needs. It does not have to use every prop passed by the parent.
Example
function Product(props) {
return <h2>Product: {props.name}</h2>;
}
function App() {
return (
<Product
name="Wireless Mouse"
price={799}
category="Electronics"
/>
);
}
export default App;
The Product component receives all three props but displays only the name. The price and category are available but are not used in its output.
7. Accessing String Props
String props contain text, such as a name, title, label, or description. When a string is passed through a JSX attribute using quotation marks, it can be accessed inside the component.
Example
function Course(props) {
return <h2>Course Name: {props.courseName}</h2>;
}
function App() {
return <Course courseName="React JS Training" />;
}
export default App;
Output: Course Name: React JS Training
8. Accessing Number Props
Number props are useful for values such as age, quantity, price, score, and experience. Numbers are usually passed using curly braces in JSX.
Example
function Score(props) {
return <p>Your score is {props.marks}.</p>;
}
function App() {
return <Score marks={95} />;
}
export default App;
Output: Your score is 95.
Remember that marks={95} passes a number, while marks="95" passes a string.
9. Accessing Boolean Props
Boolean props contain either true or false. They are useful for representing conditions, such as whether a user is logged in, a product is available, or a feature is enabled.
Example
function AccountStatus(props) {
return (
<p>
{props.isActive ? "Account is active" : "Account is inactive"}
</p>
);
}
function App() {
return <AccountStatus isActive={true} />;
}
export default App;
Output: Account is active
A boolean prop can also be passed in shorthand form, such as <AccountStatus isActive />, which sets it to true.
10. Accessing Array Props
An array can be passed as a prop when a component needs to display a list of values. The receiving component can access the array and use JavaScript methods such as map() to render its items.
Example
function Skills({ skills }) {
return (
<div>
<h2>Technical Skills</h2>
<ul>
{skills.map((skill) => (
<li key={skill}>{skill}</li>
))}
</ul>
</div>
);
}
function App() {
const skillList = ["HTML", "CSS", "JavaScript", "React"];
return <Skills skills={skillList} />;
}
export default App;
The Skills component accesses the array through the skills prop and displays each value in a list. This example uses each unique skill string as a key; for real data, use stable unique IDs when available.
11. Accessing Object Props
An object prop is useful when multiple related properties need to be passed together. The child component can access the object's individual values using dot notation.
Example
function UserProfile({ user }) {
return (
<div>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>City: {user.city}</p>
</div>
);
}
function App() {
const userData = {
name: "Rahul",
email: "[email protected]",
city: "Mumbai"
};
return <UserProfile user={userData} />;
}
export default App;
Here, user is the prop, while user.name, user.email, and user.city access properties of the object passed to it.
12. Accessing Props Inside Conditional Rendering
Props can be used with conditional expressions to determine what a component should display. The ternary operator is a common way to render different content based on a prop.
Example
function LoginMessage({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? (
<h2>Welcome back!
```html <h2>Welcome back!</h2> ) : ( <h2>Please log in.</h2> )} </div> ); } function App() { return ( <div> <LoginMessage isLoggedIn={true} /> <LoginMessage isLoggedIn={false} /> </div> ); } export default App;
The LoginMessage component accesses the isLoggedIn prop and displays the appropriate message.
13. Accessing Props in Inline Styling
Props can control a component's inline styles. This makes it possible to reuse the same component with different colors, sizes, and other style values.
Example
function Badge({ label, color }) {
return (
<span
style={{
backgroundColor: color,
color: "white",
padding: "8px 12px",
borderRadius: "6px"
}}
>
{label}
</span>
);
}
function App() {
return (
<div>
<Badge label="Success" color="green" />
<Badge label="Warning" color="orange" />
<Badge label="Error" color="red" />
</div>
);
}
export default App;
In this example, the Badge component reads label and color props and uses them to customize the displayed badge.
14. Accessing Props in Event Handlers
A component can read props inside event-handler functions. For example, a button component can receive a message and display it when clicked.
Example
function MessageButton({ message }) {
function handleClick() {
alert(message);
}
return (
<button onClick={handleClick}>
Show Message
</button>
);
}
function App() {
return <MessageButton message="Welcome to React JS!" />;
}
export default App;
The handleClick function reads the message value provided through props. When the button is clicked, it displays that message.
15. Accessing the children Prop
When content is placed between a component's opening and closing JSX tags, React makes that content available through the special children prop.
Example
function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}
function App() {
return (
<Card>
<h2>React JS Training</h2>
<p>Learn components and props.</p>
</Card>
);
}
export default App;
The Card component accesses children and displays the nested heading and paragraph inside its wrapper. This pattern is useful for cards, panels, layouts, and reusable containers.
16. Setting Default Values While Accessing Props
You can provide default values using JavaScript destructuring. A default is used when the prop is missing or has the value undefined.
Example
function Greeting({ name = "Guest", language = "English" }) {
return (
<div>
<h2>Welcome, {name}!</h2>
<p>Language: {language}</p>
</div>
);
}
function App() {
return (
<div>
<Greeting name="Rahul" language="Hindi" />
<Greeting />
</div>
);
}
export default App;
Output:
Welcome, Rahul!
Language: Hindi
Welcome, Guest!
Language: English
If a prop is explicitly set to null or an empty string, the default value is not automatically substituted.
17. Accessing Props in Reusable Components
Props allow a component to be reused with different data. Each instance accesses the values supplied by the parent when that component is rendered.
Example: Product Cards
function ProductCard({ name, price, category }) {
return (
<div className="product-card">
<h2>{name}</h2>
<p>Price: ₹{price}</p>
<p>Category: {category}</p>
</div>
);
}
function App() {
return (
<div>
<ProductCard name="Keyboard" price={1200} category="Electronics" />
<ProductCard name="Notebook" price={80} category="Stationery" />
<ProductCard name="Backpack" price={900} category="Accessories" />
</div>
);
}
export default App;
The ProductCard component accesses the name, price, and category props to display each product. The same component can be used for many products without duplicating its markup.
18. Accessing Props in Class Components
Although modern React development commonly uses functional components, you may encounter class components in existing projects. In a class component, props are accessed through this.props.
Example
import { Component } from "react";
class Greeting extends Component {
render() {
return <h2>Hello, {this.props.name}!</h2>;
}
}
export default function App() {
return <Greeting name="Priya" />;
}
Here, this.props.name accesses the name prop. In functional components, you instead use the function parameter or destructuring.
19. What Happens When Props Change?
Props are not necessarily fixed forever. When a parent component renders a child with new prop values, React renders the child with the updated values as needed.
Example
import { useState } from "react";
function Greeting({ name }) {
return <h2>Hello, {name}!</h2>;
}
function App() {
const [name, setName] = useState("Rahul");
return (
<div>
<Greeting name={name} />
<button onClick={() => setName("Priya")}>
Change Name
</button>
</div>
);
}
export default App;
Initially, Greeting displays “Hello, Rahul!”. After the button is clicked, the parent updates its state and passes the new name prop. Greeting then displays “Hello, Priya!”.
Important: The child does not change its prop directly. The parent updates its state and provides the new value.
20. Props vs State
Props and state both affect what a component displays, but they serve different purposes.
| Feature |
Props |
State |
| Purpose |
Provide inputs to a component |
Store data that can change over time |
| Managed by |
Usually the parent component |
The component that owns the state |
| Access |
Through props or destructuring |
Through a state variable and its setter |
| Direct modification |
Should not be modified by the receiving component |
Updated using the appropriate state setter |
| Example |
A product's name passed to a card |
Whether a dropdown is open |
21. Common Mistakes When Accessing Props
- Using an incorrect prop name: If the parent passes
userName, accessing props.username will not retrieve that value because JavaScript property names are case-sensitive.
- Forgetting curly braces in JSX: Use
age={21} for a number rather than age="21" if a numeric value is intended.
- Forgetting to receive props: Make sure the component declares a parameter or destructures the properties it needs.
- Trying to change props: Treat props as read-only inputs.
- Accessing a missing object property: Check that nested objects exist before accessing their properties when data may be absent.
- Confusing props with state: Use state for values that the component manages and changes over time.
- Calling an event handler immediately: Use
onClick={handleClick} when the function should run on a click, rather than calling it during rendering.
- Using spread syntax everywhere: Forward props with
{'...props'} only when passing all of them is intentional.
22. Best Practices for Accessing Props
- Use descriptive prop names that explain the purpose of each value.
- Use destructuring when it improves readability.
- Provide default values for optional props where appropriate.
- Keep components focused and reusable.
- Check potentially missing or optional data before reading nested properties.
- Do not mutate props or objects received through props.
- Use the children prop to create flexible wrapper components.
- Use Context when data must be shared across many levels and passing props becomes inconvenient.
- Use TypeScript or an appropriate validation approach in larger projects to document expected prop shapes.
23. Practical Project: User Profile
Create a reusable UserProfile component that accesses a user's name, email, city, and skills from props.
Step 1: Create UserProfile.jsx
function UserProfile({ user }) {
return (
<div className="user-profile">
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>City: {user.city}</p>
<h3>Skills</h3>
<ul>
{user.skills.map((skill) => (
<li key={skill}>{skill}</li>
))}
</ul>
</div>
);
}
export default UserProfile;
Step 2: Use UserProfile in App.jsx
import UserProfile from "./UserProfile";
function App() {
const user = {
name: "Manish",
email: "[email protected]",
city: "Mumbai",
skills: ["HTML", "CSS", "JavaScript", "React"]
};
return (
<div>
<h1>User Profile</h1>
<UserProfile user={user} />
</div>
);
}
export default App;
Step 3: Add CSS in App.css
.user-profile {
max-width: 400px;
padding: 20px;
margin: 20px auto;
border: 1px solid #cccccc;
border-radius: 8px;
background-color: #f8f9fa;
}
.user-profile h2 {
margin-top: 0;
}
.user-profile li {
margin-bottom: 6px;
}
Project Explanation
- App creates a user object containing profile details.
- App passes the object to UserProfile through the user prop.
- UserProfile accesses individual object properties using expressions such as
user.name.
- The component accesses the skills array and renders it as a list.
- The same component can display another user's information by receiving a different object.
24. Interview Questions and Answers
Q1. What does accessing props mean in React?
Answer: It means reading values passed to a component by its parent so the component can display or use that information.
Q2. How can you access props in a functional component?
Answer: Use the props object, such as props.name, or destructure the values in the function parameter, such as function Student({ name }).
Q3. What is props destructuring?
Answer: Destructuring is a JavaScript feature that extracts properties from an object into variables, making component code more concise.
Q4. How do you access props in a class component?
Answer: Use this.props, for example this.props.name.
Q5. Can props contain objects and arrays?
Answer: Yes. Props can carry different JavaScript values, including objects, arrays, functions, booleans, numbers, strings, and JSX.
Q6. What is the children prop?
Answer: It contains the content nested between a component's opening and closing JSX tags.
Q7. Can a child component change its props?
Answer: No. Props should be treated as read-only. The parent can update its state and pass new prop values.
Q8. What happens when a prop changes?
Answer: React renders the component with the new prop values when an update requires it.
Q9. How do you set a default value for a prop?
Answer: Use a default value in destructuring, such as function Greeting({ name = "Guest" }).
Q10. What is the difference between props and state?
Answer: Props are inputs received by a component, while state is data managed by a component or its owner that can change over time.
25. Practice Exercises
- Create a Greeting component that accesses a name prop and displays a personalized message.
- Create a Product component that accesses productName, price, and category props.
- Create an Employee component that displays name, department, and experience using destructuring.
- Create a Skills component that receives an array of skills and renders them in a list.
- Create a UserProfile component that receives an object with name, email, and city.
- Create a LoginMessage component that accesses a boolean prop and conditionally displays a message.
- Create a Card component that accesses and displays nested JSX through children.
- Create a button component that accesses a message prop inside an event handler.
- Set default values for two optional props in a component.
- Build three reusable product cards by passing different props to the same component.
26. Quick Revision Checklist
- Understand what props are and why they are used.
- Access props through dot notation.
- Use destructuring to access individual props.
- Access strings, numbers, booleans, arrays, and objects correctly.
- Understand how to access children and function props.
- Set default values for optional props.
- Understand how updated props affect rendering.
- Remember that props are read-only.
- Know the difference between props and state.
- Complete the User Profile project and practice the interview questions.
27. Conclusion
Accessing props is an essential React JS skill. It enables components to read information supplied by their parents and use it to render dynamic, reusable interfaces. You can access props through the props object or JavaScript destructuring, and you can work with many types of values, including strings, numbers, booleans, arrays, objects, functions, and JSX.
By practicing these techniques, you will be better prepared to build reusable components, understand parent-child communication, and move on to React topics such as state, event handling, and Context.
28. React JS Training Resources
Explore the React JS course and register for a course demo using the links below:
29. Official React Documentation
Read the official React guide for additional explanations and examples: Passing Props to a Component – React Documentation.