techStackGuru

React Children Prop


Children props in React let you pass components, elements, or even plain text as children to a parent component. You can nest and compose components in a flexible way. A component's children prop is available by default and is typically used when you want to render content between its opening and closing tags.

Example

import React from 'react';

const Card = ({ children }) => {
  return (
    <div className="card">
      {children}
    </div>
  );
};

const App = () => {
  return (
    <div>
      <Card>
        <h2>Welcome to My Website</h2>
        <p>This is a sample card component.</p>
      </Card>
    </div>
  );
};

export default App; 

This example illustrates a Card component accepting a children prop. Content will be rendered inside the card component using the children prop.

Our App component uses the Card component as its parent and provides the desired content to it as its children. It will display the Card component with the provided content as its children when the App component is rendered.

Example 2

import React from 'react';

const Button = ({ children, onClick }) => {
  return (
    <button onClick={onClick}>
      {children}
    </button>
  );
};

const App = () => {
  const handleClick = () => {
    console.log('Button clicked!');
  };

  return (
    <div>
      <Button onClick={handleClick}>
        Click me!
      </Button>
    </div>
  );
};

export default App; 

We use the Button component in the App component and provide it with the handleClick function as an onClick prop. A Button component passes the text "Click me!" as a children prop. In response to a button click, the handleClick function is executed, and "Button clicked!" is logged to the console.