You are currently viewing React Props: Passing Data Between Components
React Props

React Props: Passing Data Between Components

Introduction

One of the most fundamental concepts in React is props (short for properties). Props allow us to pass data from one component to another, making React applications dynamic and reusable. Understanding how to use React props effectively is crucial for building scalable applications.

React State: Managing Data in Components

In this article, we will cover:

  • What React props are and why they are important
  • How to pass props from a parent component to a child component
  • Using default props and prop types for validation
  • The difference between props and state
  • Best practices for using props effectively

By the end of this guide, you will be able to use props efficiently in your React applications to create modular and maintainable components. πŸš€


1. What are Props in React?

Props (short for properties) are a way to pass data from a parent component to a child component in React. Props help in making components reusable and dynamic.

1.1 Key Features of Props

βœ… Props are immutable (cannot be changed inside the component)
βœ… Props are passed from parent to child
βœ… Props make components reusable and dynamic

1.2 Example of Props in React

Let’s create a simple Greeting Component where we pass the user’s name as a prop.

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

function App() {
  return <Greeting name="Ali" />;
}

export default App;

βœ… The name prop is passed from App (parent) to Greeting (child), making it dynamic.


2. Passing Props in Functional Components

In functional components, props are passed as an argument to the function.

2.1 Example: Displaying a User Card

function UserCard(props) {
  return (
    <div className="user-card">
      <h2>{props.name}</h2>
      <p>Email: {props.email}</p>
    </div>
  );
}

function App() {
  return (
    <div>
      <UserCard name="Ali" email="ali@example.com" />
      <UserCard name="Sara" email="sara@example.com" />
    </div>
  );
}

export default App;

βœ… The UserCard component is reusable because different props can be passed.


3. Passing Props in Class Components

Before React Hooks, class components were used to handle state and props. In class components, props are accessed using this.props.

Example: Class Component with Props

import React, { Component } from "react";

class Welcome extends Component {
  render() {
    return <h1>Welcome, {this.props.name}!</h1>;
  }
}

function App() {
  return <Welcome name="Ali" />;
}

export default App;

βœ… In class components, props are accessed using this.props.


4. Default Props in React

Sometimes, we want a default value for a prop in case it is not provided. React allows us to define default props using defaultProps.

Example: Setting Default Props

function Button(props) {
  return <button>{props.label}</button>;
}

Button.defaultProps = {
  label: "Click Me", // Default value
};

function App() {
  return (
    <div>
      <Button /> {/* Uses default label */}
      <Button label="Submit" />
    </div>
  );
}

export default App;

βœ… The first Button uses the default label, while the second one overrides it.


5. Prop Types for Validation

To avoid bugs, we can enforce prop types using the prop-types library.

5.1 Installing Prop Types

Run the following command to install it:

npm install prop-types

5.2 Example: Using Prop Types for Validation

import PropTypes from "prop-types";

function UserProfile({ name, age }) {
  return (
    <div>
      <h2>{name}</h2>
      <p>Age: {age}</p>
    </div>
  );
}

// Define prop types
UserProfile.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired,
};

function App() {
  return <UserProfile name="Ali" age={25} />;
}

export default App;

βœ… If the wrong type is passed, React throws a warning in the console.


6. Passing Functions as Props

We can also pass functions as props, allowing child components to communicate with parent components.

6.1 Example: Button Component Triggering Parent Function

function Button({ onClick }) {
  return <button onClick={onClick}>Click Me</button>;
}

function App() {
  function handleClick() {
    alert("Button Clicked!");
  }

  return <Button onClick={handleClick} />;
}

export default App;

βœ… The Button component calls the function passed as a prop when clicked.


7. Passing Props Using the Spread Operator (...props)

If a component has many props, we can use the spread operator (...) for cleaner code.

7.1 Example: Passing Multiple Props Using Spread Operator

function Profile({ name, age, email }) {
  return (
    <div>
      <h2>{name}</h2>
      <p>Age: {age}</p>
      <p>Email: {email}</p>
    </div>
  );
}

function App() {
  const user = { name: "Ali", age: 25, email: "ali@example.com" };

  return <Profile {...user} />;
}

export default App;

βœ… The spread operator (...user) passes all object properties as props.


8. Props vs State in React

FeaturePropsState
DefinitionData passed from parent to childData managed inside a component
Mutable?❌ Immutableβœ… Mutable
Who updates it?Parent componentComponent itself
Used for?Configuration & data sharingManaging component behavior

πŸ’‘ Use props for data passing and state for component-specific logic.


9. Best Practices for Using Props

βœ… Keep Props Read-Only β†’ Never modify props inside a component.
βœ… Use Default Props β†’ Provide default values to avoid errors.
βœ… Use Prop Types β†’ Validate props for better debugging.
βœ… Use the Spread Operator (...props) β†’ Cleaner code when passing multiple props.
βœ… Pass Functions as Props β†’ Enable parent-child communication.


10. Real-World Example: Passing Props in a Shopping Cart

Let’s create a ShoppingCart component that displays ProductItem components with dynamic props.

10.1 ProductItem Component

function ProductItem({ name, price }) {
  return (
    <div className="product">
      <h3>{name}</h3>
      <p>Price: ${price}</p>
    </div>
  );
}

10.2 ShoppingCart Component

function ShoppingCart() {
  const products = [
    { name: "Laptop", price: 999 },
    { name: "Phone", price: 599 },
    { name: "Headphones", price: 199 },
  ];

  return (
    <div>
      <h2>Shopping Cart</h2>
      {products.map((product, index) => (
        <ProductItem key={index} {...product} />
      ))}
    </div>
  );
}

export default ShoppingCart;

βœ… Each ProductItem receives props dynamically! πŸŽ‰


Conclusion

In this guide, we explored:
βœ… What props are and how they pass data between components
βœ… How to use props in functional and class components
βœ… The importance of default props and prop types
βœ… Passing functions and objects as props
βœ… Best practices for writing clean and reusable components

Props are essential for making React components flexible and dynamic. By mastering props, you can build scalable and maintainable React applications with ease! πŸš€