import React, { useState } from 'react'; // Create a small, reusable component for an individual item function ListItem({ title, description }) { const [isExpanded, setIsExpanded] = useState(false); return ( <div> <div onClick={() => setIsExpanded(!isExpanded)}> <strong>{title}</strong> </div> {isExpanded && <div>{description}</div>} </div> ); } // Create a larger component to manage a list of items function ItemList({ items }) { return ( <div> {items.map((item, index) => ( <ListItem key={index} title={item.title} description={item.description} /> ))} </div> ); } // Render the ItemList component in the parent component function App() { const sampleItems = [ { title: 'Item 1', description: 'Description for Item 1' }, { title: 'Item 2', description: 'Description for Item 2' }, { title: 'Item 3', description: 'Description for Item 3' }, ]; return ( <div> <h1>Dynamic Item List</h1> <ItemList items={sampleItems} /> </div> ); } export default App;
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter