Props and state
Pass data with props
Give a child component data through JSX attributes and read those values from the component parameter.
Props are the inputs to a component. The parent chooses them for the current render.
function Greeting({ name, unreadCount }) {
return (
<p>
Hello, {name}. You have {unreadCount} unread messages.
</p>
)
}
export default function App() {
return <Greeting name="Ada" unreadCount={3} />
}
Quoted values are strings. Braces pass JavaScript values, so unreadCount={3} passes a number.
When App renders again with different props, React calls Greeting again. The child receives a new snapshot of those values and returns matching JSX.
Props can contain strings, numbers, objects, arrays, functions, and JSX. Keep the interface focused. If a component needs many unrelated props, it may have too many responsibilities.
The child should not need to know where the data came from. It might come from state, a route, or a server response. It only needs the contract represented by its props.
Render two greetings with different values. Then deliberately pass unreadCount="3" and inspect the type. JSX does not infer a number from a quoted attribute.
Lesson completed