Passing children as props is useful when we render child components dynamically. In this scenario, we don't know the content to render ahead of time. Some examples are reusable custom components such as Cards and generic containers.
When passing children as props, the contents of a JSX component tag body are passed to the component as props.children.
For example:
<Card><div>Card content</div></Card>, the Card component receives the <div>Card content</div> as props.children.
In the example, we use a simple Card component to display a styled div with contents passed as child props. We use typescript to enforce type safety. If you prefer plain Javascript, feel free to remove the type interfaces and prop types from the sample code.
import React from 'react';
import { Card } from './components/ui/Card';
export const App = () => {
return (
<Card
className="anyclass"
style={{backgroundColor:"green", height:"100px", width:"240px"}>
<div>1</div>
<div>2</div>
<input type="text"/>
<button>OK</button>
</Card>
);
}
export default App;
Note that we pass props to the Card component in two different ways.
1.
2. The contents within the
import { ReactNode } from "react"
export interface CardProps {
className?: string
children: ReactNode
style?: style
}
interface style{
backgroundColor: string
height?: string
width?: string
}
export const Card = (props: CardProps) => {
return(
<div className={props.className} style={props.style}>
{props.children}
</div>
)
}
Note that we supplied the Card component with a style and a class. It is important to apply that style and class to the div in the Card component to take effect.