What Are React Components?

🧱 What Are React Components? 

📌 What Are Components in React?

In React, components are the building blocks of your user interface (UI). Think of them like LEGO pieces—each one is a small, self-contained unit that you can combine to create complex layouts and features.

A React component is essentially a JavaScript function (or class) that returns a piece of JSX, which looks like HTML. You can reuse these components anywhere in your app.


☕ Real-Life Example: Coffee Shop Website

Let’s say you’re building a coffee shop website. You can break down your UI into small, meaningful components like this:

css

☕ App (entire website) ┣ 📌 Header ┣ 🛒 Menu ┃ ┣ 🧱 MenuItem (individual coffee card) ┣ 📞 Contact ┣ 📦 Footer

Each of these elements is a separate component in React.


🛠️ How React Components Work

✅ 1. Functional Components

The most common type is the functional component, which is a simple JavaScript function that returns JSX.

jsx

function Header() { return ( <header className="bg-brown-700 text-white p-4 text-center"> <h1>Coffee Time ☕</h1> </header> ); }

✅ 2. Props: Passing Data to Components

Props (short for "properties") let you pass data from one component to another.

jsx

function MenuItem({ name, price }) { return ( <div className="p-4 border rounded shadow"> <h2 className="text-xl font-bold">{name}</h2> <p className="text-gray-600">Price: ₹{price}</p> </div> ); } // Usage: <MenuItem name="Cappuccino" price={150} /> <MenuItem name="Latte" price={180} />

✅ 3. useState: Adding Interactivity

React also lets you add interactivity through state. Here’s a simple example using useState to track how many cups of coffee have been ordered.

jsx

import { useState } from 'react'; function CoffeeCounter() { const [cups, setCups] = useState(0); return ( <div className="text-center"> <p>You’ve ordered {cups} cup(s)</p> <button onClick={() => setCups(cups + 1)} className="bg-green-600 text-white px-4 py-2 rounded mt-2" > Add Cup </button> </div> ); }

📦 Putting It All Together

Here's how you might bring all these components into your main App component:

jsx

function App() { return ( <div> <Header /> <MenuItem name="Espresso" price={120} /> <MenuItem name="Mocha" price={160} /> <CoffeeCounter /> </div> ); } export default App;

🚀 Why Use Components in React?

  • Reusability: Write once, use anywhere

  • Cleaner Code: Smaller, isolated blocks are easier to manage

  • Scalability: Build large applications without complexity

  • Better Performance: Updates only what changes


🎯 Final Thoughts

React components are the heart of every modern React app. Once you understand how they work and how to use props and state, building interactive and scalable UIs becomes much easier.

Whether you're building a portfolio, a coffee shop site, or a full-scale web app—understanding React components is the first big step in becoming a professional front-end developer.

Post a Comment

0 Comments