Props object
a container for props
The component being a function, we may wonder what parameter should we declare it with.
We technically don't need to declare a parameter. In that case, the component produces the same markup whenever used.
If we instead do expect something from the caller, the pattern is for React to gather up everything in a single object parameter. By convention, we call this object props, simply because it contains the props passed down by React.
function Home(props: Object) {}
a contract
We usually set up a contract between the component and its caller: The component declares a list of props it expects to receive. It is then up to the caller to provide them, in the form of custom attributes.
In this example, the contract is about a single prop called x of type number:
function Home(props: { x: number }) {
// props.x
}
// caller
;<Home x={3} />
the children prop
When the caller nests some elements inside, React packs them into a special prop called children
, whose type is ReactNode
.
<Container>
<div>Hello</div>
<div>World!</div>
</Container>
The pattern is used for a Container component, which has to work with some piece of markup: We prefer to provide the markup in the form of nested JSX, rather than through an attribute that would be called children.
function Container(props: { children: ReactNode }) {
return (
<>
{" "}
// perform a specific layout
{children}
</>
)
}