23 Apr 2023

Passing props to a Component in React

Example props

  • className
  • src
  • width

Basic Usage

Define component:

function Avatar({person, size}) {
    return (
        <img
            className="avatar"
            src="www.avatarurl.com"
            alt="person.name"
            width="size"
            height="size"
        />
    );
}

Pass props:

export default function Profile() {
    return (
        <Avatar
            person={{ name: "Carol", occupation: "Software Developer"}}
            size={100}
        />
    );
}   

Other ways to access props

function Avatar(props) {
    let person = props.person;
}

or

function Avatar({person, size}) {
    // ...
}

You can also specify the default value of a prop:

function Avatar({person, size = 100}) {
    // ...
}

Forwarding props with JSX spread syntax

Instead of this:

<div className="card">
    <Avatar
        person={person}
        size={size}
    />
</div>

Do this:

<div className="card">
    <Avatar {...props} />
</div>

The children prop

You can also pass JSX to a component. The component will receive it as a prop called children:

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

<Card>
    <Avatar />
</Card>