Passing Props to Components in React JS
Topic: Passing Props to Components
Course: React JS Training
1. Introduction to Passing Props to Components
In React JS, props (short for properties) are used to pass data from one component to another. They allow a parent component to send information to a child component so that the child can display or use that information.
Passing props is an important concept in React because it helps developers create reusable, flexible, and dynamic components instead of writing separate code for every item.
For example, suppose a website displays three student profiles. Instead of creating three different components, you can create one reusable Student component and pass each student's name, age, and course as props.
Example
function Student(props) {
return <h2>Student Name: {props.name}</h2>;
}
function App() {
return (
<div>
<Student name="Rahul" />
<Student name="Priya" />
<Student name="Amit" />
</div>
);
}
export default App;
Output:
Student Name: Rahul
Student Name: Priya
Student Name: Amit
Here, the App component passes a different name to the same Student component each time it is used.
2. What Are Props in React?
Props are read-only values received by a component from its parent. They allow components to receive data such as strings, numbers, booleans, arrays, objects, functions, and JSX elements.
Props work similarly to function arguments. Just as a JavaScript function accepts arguments, a React component receives props and uses them to determine what should appear on the screen.
Example
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return <Greeting name="Manish" />;
}
export default App;
In this example, the Greeting component receives the value "Manish" through the name prop and displays it.
3. Why Do We Pass Props to Components?
- Reusability: Use one component with different data.
- Dynamic content: Display information based on the values received.
- Better organization: Keep components focused on specific responsibilities.
- Maintainability: Update reusable component logic in one place.
- Parent-child communication: Send data from a parent component to its child.
- Customization: Change a component's appearance or behavior using props.
4. Understanding Parent and Child Components
A parent component is a component that renders another component. The component being rendered is called the child component.
When the parent writes JSX such as <Student name="Rahul" />, it passes the name prop to the Student child component.
Example
function Student(props) {
return <p>Name: {props.name}</p>;
}
function Classroom() {
return (
<div>
<h2>Student Details</h2>
<Student name="Rahul" />
</div>
);
}
export default Classroom;
Explanation:
- Classroom is the parent component.
- Student is the child component.
- The parent passes the name prop.
- The child reads the prop and renders the student's name.
5. Basic Syntax for Passing Props
Props are passed to a component using attributes in JSX. The attribute name becomes the prop name, and its assigned value becomes the prop value.
Syntax
<ComponentName propName="value" />
Example
function Welcome(props) {
return <h1>Welcome, {props.username}</h1>;
}
function App() {
return <Welcome username="Rahul" />;
}
export default App;
In this example, username is the prop name and Rahul is its value.
6. Passing String Props
String props are used to pass text from a parent component to a child component. A string value can be written inside quotation marks in JSX.
Example
function Course(props) {
return <h2>Course: {props.courseName}</h2>;
}
function App() {
return <Course courseName="React JS" />;
}
export default App;
Output: Course: React JS
String props are useful for names, headings, descriptions, labels, and other text-based content.
7. Passing Number Props
To pass a number as a prop, use curly braces in JSX. Without curly braces, a value written in quotation marks is treated as a string.
Example
function Student(props) {
return <p>Age: {props.age}</p>;
}
function App() {
return <Student age={21} />;
}
export default App;
Here, age receives the number 21.
Important: Use age={21} to pass a number. Writing age="21" passes a string instead.
8. Passing Boolean Props
Boolean props represent true or false values. They are useful for controlling visibility, availability, status, and conditional rendering.
Example
function UserStatus(props) {
return (
<p>
{props.isLoggedIn ? "User is logged in" : "User is logged out"}
</p>
);
}
function App() {
return <UserStatus isLoggedIn={true} />;
}
export default App;
Output: User is logged in
For a boolean prop, you can also use the shorthand <UserStatus isLoggedIn />, which passes true. To pass false explicitly, write isLoggedIn={false}.
9. Passing Multiple Props
A component can receive multiple props at the same time. Each prop should have a meaningful name that describes the information it represents.
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;
The Employee component receives name, department, and experience from its parent and uses them to display employee details.
10. Accessing Props Using the props Object
A functional component receives one props object as its parameter. You can access individual values by using dot notation, such as props.name or props.age.
Example
function Product(props) {
return (
<div>
<h2>{props.name}</h2>
<p>Price: ₹{props.price}</p>
</div>
);
}
function App() {
return <Product name="Keyboard" price={1200} />;
}
export default App;
This approach is easy to understand when you are first learning props. However, destructuring is often preferred when a component uses several individual props.
11. Passing Props Using Destructuring
Destructuring is a JavaScript feature that extracts properties from an object into individual variables. React developers commonly use it to access props directly in the component parameter.
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="Rahul" age={22} course="React JS" />;
}
export default App;
Destructuring makes the code shorter and avoids repeatedly writing props. before each property.
12. Passing Array Props
Arrays can be passed as props when a component needs to receive a list of values. Use curly braces to pass the array expression.
Example
function Skills({ skills }) {
return (
<div>
<h2>Skills</h2>
<ul>
{skills.map((skill, index) => (
<li key={index}>{skill}</li>
))}
</ul>
</div>
);
}
function App() {
const skillList = ["HTML", "CSS", "JavaScript", "React"];
return <Skills skills={skillList} />;
}
export default App;
The Skills component receives an array and uses the map method to display each item. For dynamic lists where items have stable identifiers, prefer those identifiers as keys instead of array indexes.
13. Passing Object Props
Objects are useful when several related values belong together. Instead of passing each value separately, you can pass one object as a prop.
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: "Amit",
email: "[email protected]",
city: "Mumbai"
};
return <UserProfile user={userData} />;
}
export default App;
In JSX, user={userData} passes the object stored in userData to the child component. The child can then read its properties.
14. Passing Function Props
React also allows you to pass functions as props. This is especially useful when a child component needs to notify its parent that an event has occurred.
Example
function Child({ onGreet }) {
return <button onClick={onGreet}>Greet Parent</button>;
}
function App() {
function handleGreet() {
alert("Hello from the child component!");
}
return <Child onGreet={handleGreet} />;
}
export default App;
Here, App passes the handleGreet function to Child through the onGreet prop. When the button is clicked, the child calls the function provided by its parent.
Note: Passing a function through props is not the same as calling it immediately. Use onClick={handleGreet}, not onClick={handleGreet()} for this common event-handler pattern.
15. Passing JSX as Props and Using children
When JSX content is placed between a component's opening and closing tags, React passes that content to the component through a special prop called children.
Example
function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}
function App() {
return (
<Card>
<h2>React JS</h2>
<p>Learn reusable components.</p>
</Card>
);
}
export default App;
The Card component receives the heading and paragraph as children and renders them inside its wrapper. This pattern is useful for cards, layouts, modals, panels, and reusable containers.
16. Providing Default Values for Props
A component can define a default value for a prop using destructuring. The default is used when the prop is missing or its value is undefined.
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!
The default value is used for a missing or undefined name. If you explicitly pass null or an empty string, the default value is not automatically applied.
17. Passing Props to Reusable Components
One of the biggest benefits of props is that the same component can be reused with different values. This reduces duplication and makes applications easier to maintain.
Example: Reusable Button
function Button({ label, color }) {
return (
<button style={{ backgroundColor: color, color: "white" }}>
{label}
</button>
);
}
function App() {
return (
<div>
<Button label="Save" color="green" />
<Button label="Delete" color="red" />
<Button label="Cancel" color="gray" />
</div>
);
}
export default App;
All three buttons use the same Button component but receive different labels and colors.
18. Passing Props Through Intermediate Components
Sometimes data must travel from a parent to a deeply nested child. If intermediate components simply forward the same props, the pattern can become repetitive. This is commonly called prop drilling when it occurs across multiple levels.
Example
function Message({ text }) {
return <p>{text}</p>;
}
function Panel({ text }) {
return <Message text={text} />;
}
function App() {
return <Panel text="Welcome to React" />;
}
export default App;
Here, App passes text to Panel, and Panel passes it to Message. For small component trees, this is perfectly reasonable. If many levels need to forward the same data, consider component composition or React Context when appropriate.
19. Forwarding Props with the Spread Syntax
JavaScript spread syntax can forward several props from one component to another. It can reduce repetitive code when a component intentionally passes all received props to a child.
Example
function UserDetails({ name, city }) {
return (
<p>{name} lives in {city}.</p>
);
}
function Profile(props) {
return <UserDetails {...props} />;
}
function App() {
return <Profile name="Priya" city="Mumbai" />;
}
export default App;
The spread expression {'...props'} forwards the received properties. Use this pattern carefully so components do not pass unintended props to their children.
20. Are Props Mutable?
Props are read-only from the receiving component's perspective. A child component should not directly modify the props it receives. If the displayed data needs to change, the parent should provide updated props, often by updating its own state.
Incorrect Example
function Counter({ count }) {
count = count + 1;
return <p>Count: {count}</p>;
}
This is not the correct way to manage changing data in React. The component should render the value it receives rather than trying to change the prop.
Better Example
function Counter({ count }) {
return <p>Count: {count}</p>;
}
function App() {
return <Counter count={5} />;
}
export default App;
If the count must change interactively, the parent can manage it with state and pass the current count to the child as a prop.
21. Passing Props to Components with Conditional Rendering
Props can determine what a component displays. Conditional rendering allows a component to show different content based on a prop value.
Example
function LoginStatus({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? (
<h2>Welcome back!</h2>
) : (
<h2>Please log in.</h2>
)}
</div>
);
}
function App() {
return (
<div>
<LoginStatus isLoggedIn={true} />
<LoginStatus isLoggedIn={false} />
</div>
);
}
export default App;
This example uses the isLoggedIn prop to select which message to display.
22. Props vs State
Props and state both influence what a React component displays, but they have different roles.
| Feature |
Props |
State |
| Purpose |
Pass information into a component |
Store information that can change over time |
| Managed by |
Usually the parent component |
The component that owns the state |
| Directly modified by the receiving component? |
No |
Updated using the appropriate state setter |
| Can trigger a re-render? |
Yes, when new props are received |
Yes, when state is updated |
| Typical example |
Student name passed to a profile |
Whether a menu is open |
23. Complete Practical Project: Student Profile Cards
In this mini-project, you will create a reusable StudentCard component and pass different student details to it using props.
Step 1: Create StudentCard.jsx
function StudentCard({ name, course, age, 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}
city="Pune"
/>
<StudentCard
name="Amit Verma"
course="JavaScript"
age={23}
city="Delhi"
/>
</div>
);
}
export default App;
Step 3: Add Styling in App.css
.student-card {
border: 1px solid #cccccc;
border-radius: 8px;
padding: 16px;
margin: 12px;
max-width: 320px;
background-color: #f8f9fa;
}
.student-card h2 {
color: #1d4ed8;
}
.student-card p {
font-size: 16px;
}
Project Explanation
- StudentCard is a reusable child component.
- App is the parent component.
- Each StudentCard receives name, course, age, and city props.
- The same component renders different information for each student.
- CSS controls the visual appearance, while props control the displayed data.
24. Common Mistakes When Passing Props
- Forgetting curly braces for JavaScript values: Use
age={21} to pass a number instead of age="21".
- Using the wrong prop name: Ensure the name passed by the parent matches the name read by the child.
- Forgetting to receive props: Declare a parameter such as
function Student(props) or destructure the required values.
- Trying to modify props: Treat received props as read-only.
- Calling event handlers during render: For a click handler, use
onClick={handleClick} instead of onClick={handleClick()}.
- Overusing spread syntax: Pass only the props a child needs unless forwarding all props is intentional.
- Using unstable list keys: When rendering lists, prefer stable unique identifiers for keys.
- Confusing children with named props: Content nested inside component tags is available through the children prop.
25. Best Practices for Passing Props
- Use clear and descriptive prop names.
- Keep components small and focused on a single responsibility.
- Use destructuring when it improves readability.
- Provide sensible defaults for optional props.
- Pass related values together in an object when it makes the component API clearer.
- Avoid mutating props or objects received through props.
- Pass event-handler functions when a child needs to notify its parent.
- Use children for flexible wrapper and layout components.
- Use React Context when passing the same information through many intermediate levels becomes inconvenient.
- For larger JavaScript projects, consider TypeScript or another suitable validation approach to document and check expected prop types.
26. Interview Questions and Answers
Q1. What are props in React?
Answer: Props are read-only inputs passed to a React component, usually from its parent, to customize its content and behavior.
Q2. How do you pass props to a component?
Answer: Pass values as attributes in JSX, for example <Student name="Rahul" />.
Q3. How do you access props inside a functional component?
Answer: You can use the props object, such as props.name, or destructure values in the function parameter, such as function Student({ name }).
Q4. Can a component receive multiple props?
Answer: Yes. A component can receive multiple props, including strings, numbers, booleans, arrays, objects, functions, and JSX.
Q5. Can we change props inside a child component?
Answer: No. Props should be treated as read-only. The parent can provide new values when the data changes.
Q6. What is prop drilling?
Answer: Prop drilling is passing props through multiple intermediate components to reach a deeply nested component that needs the data.
Q7. What is the children prop?
Answer: children is a special prop that contains the JSX or other content nested between a component's opening and closing tags.
Q8. How can you set a default prop value in a functional component?
Answer: Use a default value in destructuring, for example function Greeting({ name = "Guest" }).
Q9. Can functions be passed as props?
Answer: Yes. A parent can pass a function to a child so the child can invoke it, commonly in response to an event.
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.
27. Practice Exercises
- Create a Greeting component that receives a name prop and displays a personalized greeting.
- Create a Product component that receives productName, price, and category props.
- Create a reusable Button component that receives label and color props.
- Create a StudentList component that receives an array of student names and renders them in a list.
- Create a UserProfile component that receives an object containing name, email, and city.
- Create a Notification component that receives an isVisible boolean prop and conditionally displays a message.
- Create a Card component that accepts nested JSX through the children prop.
- Create a parent component that passes a function to a child button and displays an alert when the button is clicked.
- Add default values to a component's optional props.
- Create three reusable employee profile cards using the same component with different props.
28. Quick Revision Checklist
- Understand the meaning and purpose of props.
- Know how to pass props through JSX attributes.
- Know how to receive props using the props object and destructuring.
- Practice passing strings, numbers, booleans, arrays, objects, functions, and JSX.
- Understand default values and the children prop.
- Remember that props are read-only.
- Understand how props support reusable components.
- Know the difference between props and state.
- Recognize prop drilling and understand when Context may help.
- Build and test the Student Profile Cards project.
29. Conclusion
Passing props to components is a fundamental React JS skill. Props allow parent components to share information with child components, making interfaces dynamic and reusable. By learning how to pass and receive different types of props, use destructuring, define defaults, forward functions, and render children, developers can build better-structured React applications.
Practice these examples and build small projects to become comfortable with component communication before moving on to state management and more advanced React topics.
30. React JS Training Resources
Learn more about React JS training and course details:
31. Official Documentation
For additional examples and explanations, refer to the official React documentation: Passing Props to a Component – React Docs.