techStackGuru

React children


An example of how a parent component can pass content to its child component is shown here.

In this example:

  • The ChildComponent is rendered by the ParentComponent.
  • You can place any JSX element inside the ChildComponent tags. It will be passed as a child to ChildComponent.
  • A ChildComponent renders the content passed from its parent using props.children.
  • ParentComponent.js

    import React from 'react';
    import ChildComponent from './ChildComponent';
    
    const ParentComponent = () => {
        return (
            <div>
                <ChildComponent>
                    <h2>Hello, World!</h2>
                    <p>This is some content passed as children.</p>
                </ChildComponent>
            </div>
        );
    }
    
    export default ParentComponent;
    

    ChildComponent.js

    import React from 'react';
    
    const ChildComponent = ({ children }) => {
        return (
            <div>
                <h1>Child Component</h1>
                <div>{children}</div>
            </div>
        );
    }
    
    export default ChildComponent;

    If you run this code, the ChildComponent will render its own content along with the content provided as children by the ParentComponent. Components with dynamic content are often created using this pattern in React.