1.6K Views

REACT105 - Props in React

Learn how to pass data between React components using props, understand one-way data flow, and apply best practices for reusable components.

Props (short for properties) are the primary way to pass data from one component to another in React.
In this lesson, you will learn how props work, how to use them effectively, and why they are essential for building reusable components.

What Are Props?

Props are read-only inputs passed to a component by its parent.
They allow components to be dynamic and configurable.

Think of props as function parameters for components.


Passing Props to a Component

You can pass props to a component using attributes.

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

Receiving props in the child component:

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

This makes the component reusable with different values.


Props Destructuring

Destructuring makes props easier to work with.

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

This is the most common pattern in modern React code.


Passing Multiple Props

Components can receive multiple props.

<UserCard 
  username="ekurt" 
  age={30} 
  city="Antalya" 
/>

Using them:

function UserCard({ username, age, city }) {
  return (
    <div>
      <h3>{username}</h3>
      <p>Age: {age}</p>
      <p>City: {city}</p>
    </div>
  );
}

Props Are Read-Only

Props cannot be modified inside a component.

This is not allowed:

props.name = "New Name";

React enforces one-way data flow:

Parent → Child

If data needs to change, it must be handled using state in the parent component.


Passing Functions as Props

Props can also be functions.
This allows child components to communicate with parents.

function App() {
  function handleClick() {
    console.log("Button clicked");
  }
 
  return <Button onClick={handleClick} />;
}

Child component:

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

This pattern is extremely common in React applications.


Default Props

You can define default values for props.

function Avatar({ size = 40 }) {
  return <img width={size} height={size} />;
}

If size is not provided, React uses the default value.


Children Prop

Every component automatically receives a children prop.

function Card({ children }) {
  return <div className="card">{children}</div>;
}

Usage:

<Card>
  <h2>Title</h2>
  <p>Description</p>
</Card>

This allows flexible and composable layouts.


Summary

In this lesson, you learned:

  • What props are and why they exist
  • How to pass and receive props
  • Props destructuring
  • One-way data flow in React
  • Passing functions as props
  • Default props
  • The children prop

In the next lesson, we will explore state and learn how React components manage dynamic data using the useState hook.