How to use props.children in React for flexible components

🚀 Today I Learned: props.children in React If you’ve been building components in React, you probably know how to pass data using props. But did you know you can also pass entire elements or components as children? 👶 That’s what props.children is all about — it’s a simple yet powerful concept that helps you build reusable and flexible components. --- 💡 Quick Example function Card(props) { return <div className="card">{props.children}</div>; } function App() { return ( <Card> <h2>Hello React!</h2> <p>This content is inside the Card component.</p> </Card> ); } ✅ Output: <div class="card"> <h2>Hello React!</h2> <p>This content is inside the Card component.</p> </div> The Card component doesn’t care what content it wraps — that’s decided by the parent component. This makes it perfect for things like modals, layouts, cards, and tooltips. --- 🧱 Why It’s So Useful Makes components more reusable 🧩 Keeps your UI clean and composable Reduces repetitive code --- ⚙️ Example: Mixing props.children with Other Props function Card({ title, children }) { return ( <div className="card"> <h3>{title}</h3> <div>{children}</div> </div> ); } function App() { return ( <Card title="React Magic ✨"> <p>props.children makes components super flexible!</p> </Card> ); } --- 🧠 Key Takeaway props.children = the secret ingredient for truly flexible React components. Once you get comfortable with it, you’ll start writing components like a pro. ⚛️🔥 --- 💬 What was your first “aha!” moment with React? Drop it in the comments — I’d love to hear what you’re learning this week! #ReactJS #FrontendDevelopment #JavaScript #LearningInPublic #WebDevelopment

To view or add a comment, sign in

Explore content categories