What Are React Props?

Props (short for “properties”) in React are like arguments that we give to a function. When we have a parent component and a child component, the parent can send data to the child using props.

For example, if you want to show a user’s name inside a child component, the parent can send the as a prop.

Props are read-only, which means the child component can’t change this value; it can only use it. This method is useful for one-way data flow.

How To Use Props in Functional Components?

When we pass data from a parent to a child component using props, the child needs a way to access that data. In the functional component, props are used as the first argument of the function to access them.

There are two common ways to use them:

1) Using the props object

In this method, the function will get a single argument called props, which is an object containing all the data passed from the parent.

For example:

function Profile(props) {
return <h2>{props.name} is {props.age} years old.</h2>;
}

In this code:

  • props.name → Accesses the value of the name prop.
  • props.age → Accesses the value of the age prop.

2) Using destructuring (Cleaner and Preferred)

If you don’t want to write props.name and props.age every time, you can unpack the values directly in the function parameter using destructuring.

For example:

function Profile({ name, age }) {
return <h2>{name} is {age} years old.</h2>;
}
  • We pulled out “name” and “age” from props in one step.
  • This makes the code shorter and easier to read.

Example of Passing Props

import React from "react";

// Parent Component
function App() {
return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<Greeting name="John" timeOfDay="Morning" />
</div>
);
}

// Child Component
function Greeting({ name, timeOfDay }) {
return (
<h2>
Good {timeOfDay}, {name}! Have a great day!
</h2>
);
}

export default App;

Explanation:

  • We are sending two pieces of data as props:
    • name=”John”
    • timeofDay=”Morning”
  • Child component “Greeting” receives these props and uses them to show a message: “Good Morning, John! Have a great day!”

Using Props in Class Components

Class components work differently from functional components when it comes to handling props. In class components, the component is a class that extends React.Component, not a simple function. This means the props are automatically stored inside the class instance.

import React, { Component } from "react";

// Parent Component
class App extends Component {
render() {
return (
<div style={{ textAlign: "center", marginTop: "40px" }}>
<Welcome userName="John" favoriteColor="Blue" />
</div>
);
}
}

// Child Component
class Welcome extends Component {
render() {
return (
<h2>
Hello, {this.props.userName}! Your favorite color is{" "}
<span style={{ color: this.props.favoriteColor }}>
{this.props.favoriteColor}
</span>
.
</h2>
);
}
}

export default App;

Explanation of this code:

  • These two props were sent to the welcome component.
  • Then child component (welcome) accesses props using this.props.userName and this.props.favoriteColor and displays a message like: “Hello, John! Your favorite color is Blue.”
  • The color name is also styled using the actual color passed in the prop.

Benefits of Using Props In React

1) Reusability: Props make components reusable because you can use the same component in multiple places with different data. Instead of creating separate components for every variation, you just pass different props.

2) Customizability: Props allow child components to change their behavior differently based on the data received from the parent, creating more flexible and customizable components.

3) Separation of Concerns: Props help separate data handling and UI rendering. The parent component handles data logic, while the child component focuses on displaying the data.

How To Passing Multiple Props?

When we send more than one piece of data, like name and age, from a parent component to a child component, we can pass multiple props.

Suppose the parent component is like the person packing the gift, and the child component is like the person receiving the gift. Each prop is like a different item inside the box with its label (name=”John”, age={25}).

For example, if you only pass the name, you can just show “Hello John”, but if you also pass age, you can show extra details like “You are 25 years old”.

For example: Parent Component

function ParentComponent() {
return <Greeting name="Alice" age={25} />;
}
  • We are sending two props to greet name=”John” and age={25}.

Child Component:

function Greeting({ name, age }) {
return (
<div>
<p>Hello, {name}!</p>
<p>You are {age} years old.</p>
</div>
);
}

Default Props

React allows you to set default values for props in case they are not provided by the parent component. This is useful for handling cases where certain props are optional.

Instead of leaving it empty or showing undefined, we can set a default value. That default value is called default props.

Imagine a restaurant menu; if the customer doesn’t say which drink they want, the restaurant automatically gives water. Here, water is the default drink.

function Greeting({ name }) {
return <p>Hello, {name}!</p>;
}

Greeting.defaultProps = {
name: "Guest"
};

Explanation of this code:

  • If the parent sends name=”John”, the output will be: Hello, John!
  • If the parent doesn’t send any name, the output will be: Hello, Guest!

Prop Types and Validation

When you create a component, you often pass data as props. But what if the wrong type of data is passed?

For example:

  • You expect age as a number, but the parent sends “twenty”.
  • Or you expect a name as a string, but the parent sends an array.

React will still try to render it, but it can cause unexpected issues in your app. So the solution is a way to check and validate the type of data being passed to a component during development. it does not stop the app but shows a warning in the console, so you can fix it early.

import React from 'react';
import PropTypes from 'prop-types';

function StudentProfile({ name, age, grade }) {
return (
<div style={{ border: '1px solid #ccc', padding: '10px', width: '250px', margin: '10px auto' }}>
<h2>Student Profile</h2>
<p>Name: {name}</p>
<p>Age: {age}</p>
<p>Grade: {grade}</p>
</div>
);
}

// PropTypes for type checking
StudentProfile.propTypes = {
name: PropTypes.string.isRequired, // must be a string and required
age: PropTypes.number, // should be a number
grade: PropTypes.string // should be a string
};

// Default values (in case props are missing)
StudentProfile.defaultProps = {
age: 16,
grade: "Not Assigned"
};

export default function App() {
return (
<div>
<StudentProfile name="Alice" age={17} grade="A+" />
<StudentProfile name="Bob" /> {/* Age and grade will use defaults */}
</div>
);
}

In this code:

  • We created StudentProfile that expects name, age, and grade.
  • Then we used a prototype like:
    • name → must be a string and required.
    • age → must be a number (optional).
    • grade → must be a string (optional).
  • If someone sends the wrong type or misses a required prop, React will warn in the console.

Conditional Rendering with Props

Conditional rendering means showing different content based on a condition. When we pass props to a component, those props can decide what the component should display.

Think of it like a traffic light, if the light is green, you show “Go”. If it’s red, you show “Stop”. The color green and red are like a prop that tells what to show.

In React, you can do this using the following methods:

  • if statements
  • ternary operator (condition ? doThis : doThat)
  • logical && (show only if condition is true)
import React from 'react';

function ExamStatus({ score }) {
return (
<div style={{ textAlign: 'center', padding: '20px', fontFamily: 'Arial' }}>
<h2>Exam Result</h2>
{score >= 50 ? (
<p style={{ color: 'green' }}>Congratulations! You Passed</p>
) : (
<p style={{ color: 'red' }}>Sorry, You Failed. Try Again!</p>
)}
</div>
);
}

function App() {
return (
<div>
<ExamStatus score={72} />
<ExamStatus score={35} />
</div>
);
}

export default App;

Explanation:

  • The parent (App) passes a score prop to ExamStatus.
  • Inside ExamStatus, we check if score >= 50, show Passed message. Else, show failed message.
  • We use a ternary operator for this.

Mini Project: Student Profile Cards

Now we will create a React app that displays multiple student profiles using props to pass data from a parent component to child components.

Requirements of this project:

  • Display a list of students with their name, age, and course.
  • Each profile should be a separate reusable component.
  • Props will be used to send data from the parent to the child.

Project Code:

import React from 'react';

// Child Component: Displays a single student profile
function StudentCard({ name, age, course }) {
return (
<div style={{
border: '2px solid #ccc',
borderRadius: '10px',
padding: '15px',
margin: '10px',
width: '250px',
backgroundColor: '#f9f9f9'
}}>
<h2>{name}</h2>
<p>Age: {age}</p>
<p>Course: {course}</p>
</div>
);
}

// Parent Component: Holds multiple student profiles
function StudentList() {
return (
<div style={{ textAlign: 'center' }}>
<h1>Student Profiles</h1>
<div style={{
display: 'flex',
justifyContent: 'center',
flexWrap: 'wrap'
}}>
<StudentCard name="Alice" age={20} course="React Basics" />
<StudentCard name="Bob" age={22} course="JavaScript" />
<StudentCard name="Charlie" age={19} course="Python" />
</div>
</div>
);
}

export default StudentList;
  • Now try to understand this code logic by yourself, and paste this code in your IDE, then see the results. Below we provided one exercise, so you can write that code according to your logic ideas.

Student Exercise: Conditional Rendering with Props

Task:
Create a React component named WeatherInfo that accepts a prop called temperature. The component should display the following terms:

  • If the temperature is 30 or above, show: “It’s a Hot Day!” (in red color)
  • If the temperature is below 30, show: “It’s a Cool Day!” (in blue color)

Requirements:

  • Use functional components.
  • Use props (don’t hardcode values).
  • Use ternary operator for conditional rendering.
  • Display the temperature value on the screen along with the message.

Also Learn Other Topics:

Leave a Comment