Components and Props
Components and Props
Components are the building blocks of any React app. You split your interface into logical pieces, render each with a component, and pass data between them using props.
Function components
The simplest component is a function that returns JSX:
function Card(props) {
return <div className="card">{props.children}</div>;
}
You can also destructure props for cleaner code:
function Badge({ label, color }) {
return <span style={{ backgroundColor: color }}>{label}</span>;
}
What props are
Props are read-only. A parent renders a component and passes attributes, and the child receives them as an object. This makes the data flow one way, from parent to child, which keeps behavior predictable.
Passing props down
function App() {
return (
<div>
<Badge label="New" color="tomato" />
<Badge label="Hot" color="orange" />
</div>
);
}
Here App renders the same Badge component twice with different props. Reusing Badge keeps the markup and logic in one place while the caller decides the details.
Children prop
Content placed between the opening and closing tags of a component comes through as the children prop. Wrapper components use it to lay out arbitrary content.
Rules for props
Never modify props inside a component. Props are read-only by design. If you need changing data, hold it in state instead. Also keep components focused and give them clear names so the component tree reads like a sentence.
Key Points
- Function components are plain functions returning JSX.
- Props pass read-only data from parent to child.
- Destructure props for readable component bodies.
- children passes the content between tags.
- State, not props, handles data that changes over time.