Home > References > Web Development > Reactjs references

How to pass children as props in Reactjs

Last updated : April 16, 2022

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.

Parent component passing children props


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. className and style as standard props where Card component receives them as props.className and props.style.
2. The contents within the Card component, i.e., <Card>...</Card> as children where Card component receives then as props.children.

Child component receiving children as props.children


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.

References

Lance
By: Lance
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Comments are disabled

No Comments