Skip to content

Instantly share code, notes, and snippets.

@kingluddite
Created February 8, 2024 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kingluddite/a68f8d647f53c32b8cbe29aabd2f2ab6 to your computer and use it in GitHub Desktop.
Save kingluddite/a68f8d647f53c32b8cbe29aabd2f2ab6 to your computer and use it in GitHub Desktop.
Practical use of Reacts props.children

Practical use of Reacts props.children

In React, props.children is a special prop that allows you to pass components or elements as children to another component. This is particularly useful when you want to create flexible and reusable components that can contain arbitrary content.

Here's a simple example to illustrate its use and purpose:

// ParentComponent.js
import React from 'react';

const ParentComponent = (props) => {
  return (
    <div className="parent">
      <h2>Parent Component</h2>
      {/* Render the children passed to ParentComponent */}
      {props.children}
    </div>
  );
};

export default ParentComponent;

In the ParentComponent above, props.children is used to render any child components or elements passed to it. Let's see how it can be used:

// App.js
import React from 'react';
import ParentComponent from './ParentComponent';
import ChildComponent from './ChildComponent';

const App = () => {
  return (
    <div className="app">
      {/* Passing a ChildComponent as a child of ParentComponent */}
      <ParentComponent>
        <ChildComponent />
      </ParentComponent>
    </div>
  );
};

export default App;
// ChildComponent.js
import React from 'react';

const ChildComponent = () => {
  return (
    <div className="child">
      <h3>Child Component</h3>
      <p>This is some content within the Child Component.</p>
    </div>
  );
};

export default ChildComponent;

In the App component, ChildComponent is passed as a child to ParentComponent within the JSX. When ParentComponent is rendered, it will display the content of ChildComponent because of props.children.

This pattern allows for composability and flexibility in building React components, as it allows you to nest components within each other and create complex UI structures while maintaining component reusability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment