Understanding Props in React
What are Props?
Props (short for properties) are read‑only inputs that you pass to a React component. They enable data flow from parent to child, making components reusable and configurable.
Passing Props
{`function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
function App() {
return <Greeting name="Alice" />;
}`}
Default Props
{`function Button({ label }) {
return <button>{label}</button>;
}
Button.defaultProps = {
label: 'Click me',
};`}
Prop Types Validation
{`import PropTypes from 'prop-types';
function Card({ title, count }) {
return (
<div className="card">
<h3>{title}</h3>
<p>Count: {count}</p>
</div>
);
}
Card.propTypes = {
title: PropTypes.string.isRequired,
count: PropTypes.number,
};`}
Children Prop
{`function Panel({ children }) {
return <div className="panel">{children}</div>;
}
function App() {
return (
<Panel>
<p>This is inside the panel.</p>
</Panel>
);
}`}