0
0
ReactHow-ToBeginner · 3 min read

How to Pass Children as Prop in React: Simple Guide

In React, you pass children to a component by placing elements between its opening and closing tags, which are accessible inside the component via the children prop. You can then render these children inside the component using props.children or by destructuring { children } from props.
📐

Syntax

To pass children to a React component, place the child elements between the component's tags. Inside the component, access these elements using the children prop.

  • Parent usage: Wrap content inside the component tags.
  • Child access: Use props.children or destructure { children } from props.
jsx
function Container(props) {
  return <div>{props.children}</div>;
}

// Usage
<Container>
  <p>This is a child element</p>
</Container>
Output
A div containing the paragraph: "This is a child element"
💻

Example

This example shows a Box component that wraps any children passed to it inside a styled container.

jsx
import React from 'react';

function Box({ children }) {
  return (
    <div style={{ border: '2px solid blue', padding: '10px', borderRadius: '5px' }}>
      {children}
    </div>
  );
}

export default function App() {
  return (
    <Box>
      <h2>Hello, React!</h2>
      <p>This content is passed as children.</p>
    </Box>
  );
}
Output
A blue bordered box containing a heading "Hello, React!" and a paragraph "This content is passed as children."
⚠️

Common Pitfalls

Common mistakes when passing children include:

  • Forgetting to wrap child elements inside the component tags, so children is empty.
  • Trying to pass children as a regular prop instead of placing them between tags.
  • Not rendering props.children inside the component, so children do not appear.
jsx
function Wrapper(props) {
  // Missing rendering of children
  return <div>Wrapper content only</div>;
}

// Usage with children
<Wrapper>
  <p>This will not show</p>
</Wrapper>

// Corrected version
function WrapperFixed({ children }) {
  return <div>{children}</div>;
}
Output
First Wrapper shows only "Wrapper content only" without the paragraph; WrapperFixed shows the paragraph inside a div.
📊

Quick Reference

ConceptUsageNotes
Passing childrenWrap elements inside component tagsChildren become props.children
Accessing childrenUse props.children or destructure { children }Render inside component JSX
No childrenIf no children passed, props.children is null or undefinedCheck before rendering if needed
Multiple childrenPass multiple elements inside tagsChildren can be an array of elements

Key Takeaways

Pass children by placing elements between component tags in JSX.
Access children inside the component via the props.children property.
Always render props.children in your component to display passed content.
Children can be any valid React elements, including multiple elements.
If no children are passed, props.children will be undefined or empty.