What are props in React

In React, props (short for "properties") are a way to pass data from a parent component to a child component. They are read-only and help make components reusable and dynamic.

Key Characteristics of Props:

  1. Immutable – Props cannot be modified by the child component.

  2. Passed Down – Data flows from parent to child (unidirectional).

  3. Can Be Anything – Props can be strings, numbers, arrays, objects, functions, or even other React components.

Example:

jsx
// Parent Component
function App() {
  return <Greeting name="Alice" age={25} />;
}

// Child Component (receives props)
function Greeting(props) {
  return (
    <h1>Hello, {props.name}! You are {props.age} years old.</h1>
  );
}

Using Destructuring for Cleaner Code:

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

Passing Functions as Props:

jsx
function Parent() {
  const handleClick = () => alert("Button clicked!");
  return <Child onClick={handleClick} />;
}

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

Props vs. State:

PropsState
Passed from parentManaged within the component
Read-onlyMutable (via setState or useState)
Used for configurationUsed for dynamic data

Special Props:

  • children: Accesses content between component tags.

    jsx
    function Card({ children }) {
      return <div className="card">{children}</div>;
    }
    // Usage: <Card> <h1>Title</h1> </Card>

Props are fundamental for component communication in React, enabling reusable and modular UI design.

To Top