React Mastery / React Basics

Props

Props (short for properties) are read-only inputs that are passed from one component to another in React.

They are used to send data from a parent component to a child component.

You can think of props like arguments you pass into a function — but here, you pass them into components.


🧠 Key Points

  • Props are read-only.

  • Props help make components dynamic and reusable.

  • Props are passed using JSX attributes.


🟩 What Are We Doing?

You're passing props (data) from a parent component to a child component, and the child component retrieves (accesses) those props to display or use them.


✅ How to Retrieve Props in Functional Components

🧠 What's Happening?

  • App passes a prop called name with value "Alex" to Greeting.

  • Greeting receives all props in the props object.

  • You access it using:

    👉 props.name

🔎 Step-by-Step Explanation

1. You have two components:

  • App: The parent component

  • Greeting: The child component


2. In the App component:

<Greeting name="Alex" />
  • You're using the Greeting component.

  • You are passing a prop named name with the value "Alex".

  • This is just like saying:

    props = {
      name: "Alex"
    }

3. In the Greeting component:

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}
  • props is an object that holds all the data passed to the component.

  • You access the name prop using props.name.


✅ Cleaner Way: Destructuring Props

Instead of props.name, you can destructure the props like this:

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

This works the same way but looks cleaner.


✅ How to Retrieve Props in Class Components

🧠 How It Works:

  • Class components receive props using this.props.

  • Here, this.props.name is used to retrieve the value "Alex".

🔍 Step-by-Step Explanation:

🔹 1. App Component

function App() {
  return <Greeting name="Alex" age={25} />;
}
  • This is a functional component called App.

  • It returns a JSX element: <Greeting name="Alex" age={25} />

  • It’s calling the Greeting component and passing two props:

    • name="Alex" → this means props.name = "Alex"

    • age={25} → this means props.age = 25


🔹 2. Greeting Class Component

class Greeting extends Component {
  render() {
    return (
      <h1>
        Hello, {this.props.name}! You're {this.props.age} years old.
      </h1>
    );
  }
}
  • This is a class component, created by extending React.Component.

  • Inside the class, there’s a render() method.

    • This method is required in class components—it tells what to display.

  • To access props in a class component, you use this.props.


🔹 3. What is this.props?

  • this refers to the instance of the component class.

  • this.props is an object that contains all the props passed to this component.

    • this.props.name → refers to "Alex"

    • this.props.age → refers to 25