Props
Props
stands for properties.
- Props are arguments passed into React components.
- Props are passed to components via HTML attributes.
- React Props are like function arguments in JavaScript and attributes in HTML.
Component with Props
export default function Card(props) {
return (
<>
<h1>{props.heading}</h1>
<p>{props.body}</p>
</>
);
}
Passing data through Attributes
<Card heading="My Card Heading" body="My Card Body" />
Destructuring Props
export default function Card({ heading, body }) {
return (
<>
<h1>{heading}</h1>
<p>{body}</p>
</>
);
}
Default Value for Props
export default function Card({ heading = "Sample heading", body }) {
return (
<>
<h1>{heading}</h1>
<p>{body}</p>
</>
);
}
<Card body="My Card Body" />
Passing Children
- When you nest content inside a JSX tag, the component will receive that content in a special prop called
children
.
export default function Card({ heading = "Sample heading", children }) {
return (
<>
<h1>{heading}</h1>
<div>{children}</div>
</>
);
}
<Card>
<p>content 1</p>
<p>content 2</p>
</Card>
Passing Function via Props/Raise Events
Raise Event
export default function Card({
heading = "Sample heading",
children,
onDetailClick,
}) {
return (
<>
<h1>{heading}</h1>
<div>{children}</div>
<div>
<button onClick={onDetailClick}>Details</button>
</div>
</>
);
}
Handle Event
<Card onDetailClick={() => alert("card details")}>
<p>content 1</p>
<p>content 2</p>
</Card>
Immutable
- Props reflect a component’s data at any point in time, rather than only in the beginning.
- Props are immutable (unchangeable). Don’t try to
change props
.