Skip to content

8. children

Course: React - chapter 8

The children prop allows you to pass elements or components as props to other components.

import React from 'react';
const Card = ({ children }) => {
return (
<div style={{
border: '1px solid #ccc',
borderRadius: '5px',
padding: '20px',
margin: '10px',
boxShadow: '2px 2px 5px rgba(0, 0, 0, 0.1)',
}}>
{children}
</div>
);
};
const App = () => {
return (
<div>
<Card>
<h2>Card Title</h2>
<p>This is some content inside the card.</p>
</Card>
<Card>
<h2>Another Card</h2>
<p>This card has different content!</p>
</Card>
</div>
);
};
export default App;
$1b
import React, { useState } from 'react';
const Collapsible = ({ title, children }) => {
const [isOpen, setIsOpen] = useState(false);
return (
<div>
<button onClick={() => setIsOpen(!isOpen)}>
{title} {isOpen ? '-' : '+'}
</button>
{isOpen && <div>{children}</div>}
</div>
);
};
const App = () => {
return (
<div>
<Collapsible title="Section 1">
<p>This is the content of section 1.</p>
</Collapsible>
<Collapsible title="Section 2">
<p>This is the content of section 2.</p>
</Collapsible>
</div>
);
};
export default App;