DEV Community

Ragul
Ragul

Posted on

Props in React

Props pass data from a parent component to a child component. Props are read-only — a child can't change them. Data flows one way: parent to child.

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

<Greeting name="Ragul" />
Enter fullscreen mode Exit fullscreen mode

Syntax

Props arrive as one object. You can destructure them for short code:

function Profile({ name, age }) {
  return <p>{name}, {age}</p>;
}
Enter fullscreen mode Exit fullscreen mode

Characteristics

  • Read-only — a component can't change its own props
  • One-way flow — parent to child only
  • Any type — text, numbers, booleans, arrays, objects, functions

To let a child trigger a change, the parent passes a function as a prop:

function Counter({ count, onIncrement }) {
  return <button onClick={onIncrement}>{count}</button>;
}
Enter fullscreen mode Exit fullscreen mode

children prop

Holds whatever is placed between a component's tags. Used for wrappers like cards or modals.

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

<Card><p>Nested content</p></Card>
Enter fullscreen mode Exit fullscreen mode

Default values

function Button({ label = "Submit" }) {
  return <button>{label}</button>;
}
Enter fullscreen mode Exit fullscreen mode

Props vs. State

Props State
From Parent The component itself
Changeable No Yes, via useState
Like Function arguments Local variables

Top comments (1)

Collapse
 
rsbalaji profile image
balaji s •

I learned how to pass default values from this blog.
Thank you ragul