React Component Basics
Table of Contents + −
In the previous lessons, we have learned about JSX and how it allows us to write HTML-like syntax within JavaScript.
React is all about components. Now let’s properly understand what React components are, why they’re so important, and how to create them.
🧩 What Are React Components?
React components are the basic building blocks of any React application. Here are the key points to understand about components:
• Everything is a component - In React applications, every piece of the user interface is either a component or part of a component
• Component-to-view conversion - Technically, React creates a view for each component and all these views combine to form the complete user interface or a web page.
• Foundation of React development - Understanding components is crucial because they form the foundation of how React works and how you build applications
• What React does - React’s main responsibility is taking these components and rendering them on the webpage to create the final UI
Key Concept
We can think of a component as representing a portion of the user interface. Each component describes both its functionality and its appearance.
⚙️ Key Properties of Components
Most of the React components have some key properties as follows:
Property | Description | Example |
Data (state) | Information the component manages | User profile information, product details |
Behavior (Logic) | Code that makes the component work | Click handlers, form validation, calculations |
View (UI) | How the component looks on screen | Colors, layout, typography, animations |
Every component knows what it does and how it should appear and that makes them perfect for building complete user interfaces.
🛠️ Creating Your First Component
In React, we write new components using JavaScript functions. Let’s create a simple component step by step:
import React from "react";
function ShoppingItem() { return <h2>Apples - 5 pieces</h2>;}
export default ShoppingItem;
Let’s break this down:
Part | Purpose | Requirements |
import React from "react" | Imports React library | Required to use JSX and React features |
function ShoppingItem() | Component declaration | should start with uppercase letter |
return | Returns JSX markup | Must return something |
| JSX content to render | Can be any valid JSX |
export default ShoppingItem | Exports the component | Required to use this component in other files |
Key Things to notice
Anytime you create a new component, make sure to:
- Import React at the top of the file
- Export the component as default
📏 Component Rules
There are two important rules when writing components as functions:
📦 Rule 1: Must Return JSX
The function needs to return some JSX. For Example
// ✅ Correct - returns JSXfunction ShoppingItem() { return <h2>Apples - 5 pieces</h2>;}
// ✅ Also correct - returns nullfunction EmptyComponent() { return null;}
// ❌ Wrong - doesn't return anythingfunction BadComponent() { console.log("This doesn't return JSX");}
📦 Rule 2: Must return only one parent element
The JSX returned from a component must be wrapped in a single parent element. If you need to return multiple elements, you can wrap them in a <div>
or a React Fragment (<>...</>
).
// ✅ Correct - wrapped in a divfunction ShoppingItem() { return ( <div> <h2>Apples - 5 pieces</h2> <p>Fresh and organic apples.</p> </div> );}
// ✅ Correct - wrapped in a React Fragmentfunction ShoppingItem() { return ( <> <h2>Apples - 5 pieces</h2> <p>Fresh and organic apples.</p> </> );}
// ❌ Wrong - multiple root elementsfunction BadShoppingItem() { return ( <h2>Apples - 5 pieces</h2> <p>Fresh and organic apples.</p> );}
🎯 Using Components
After creating a component, we need to use the component in our application to see it:
function App() { return ( <div> <h1>My Shopping List</h1> <ShoppingItem /> </div> );}
Self-Closing Components
When a component doesn’t have children, you can write it as self-closing: <ShoppingItem />
instead of <ShoppingItem></ShoppingItem>
.
🔄 Component Reusability
One of the most powerful features of components is reusability. Now let’s see the power of reusability. We can use the same component multiple times:
function App() { return ( <div> <h1>My Shopping List</h1> <ShoppingItem /> <ShoppingItem /> <ShoppingItem /> </div> );}
This will display three identical shopping items. While they look the same now, we’ll learn how to customize each one with different data using props in upcoming lessons.
💡 Reusability Benefits
- Write once, use everywhere - Create a component once and use it multiple times throughout your application
- Reduce code duplication - Instead of copying and pasting similar code, reuse the same component
- Easier maintenance - When you need to make changes, update the component once and it updates everywhere it’s used
- Consistent UI - Ensures all instances look and behave the same way across your application
- Faster development - Build new features by combining existing components rather than starting from scratch
For Example:
In above App
component, we can see how the ShoppingItem
component is reused multiple times to display the same item.
We can customize the ShoppingItem
component by passing different props to it that we will learn in upcoming sessions.
Golden Rule
Whenever you need some duplication in your UI, create a new component and use it as many times as necessary.
🧠 Adding Logic to Components
Since components are JavaScript functions, we can add any JavaScript logic we want:
function ShoppingItem() { // JavaScript logic goes here const itemName = "Apples"; const quantity = 5; const price = 3.99; const isUrgent = true;
console.log("ShoppingItem component is rendering");
return ( <div> <h3>{itemName}</h3> <p>Quantity: {quantity}</p> <p>Price: ${price}</p> {isUrgent && <span>🔴 Urgent Item!</span>} <p>Total: ${(quantity * price).toFixed(2)}</p> </div> );}
JavaScript in JSX
Use curly braces {}
to include JavaScript expressions inside JSX. This
allows you to display dynamic content.
⚠️ Common Mistakes to Avoid
Mistake | Problem | Solution |
Lowercase component name | React won’t recognize it as a component | Always start with uppercase: ShoppingItem not shoppingItem |
Multiple root elements | JSX syntax error | Wrap in <div> or React Fragment |
Forgetting to use the component | Component won’t appear in UI | Include it in JSX: <ShoppingItem /> |
Not returning anything | Component renders nothing | Always return JSX or null |
Thinking in Components
Learning to “think in components” is a fundamental skill for React developers. Here’s a systematic approach:
Step 1: Identify UI Sections
Look at your design and identify distinct sections that could be separate components. Ask yourself:
- Does this section have a specific purpose?
- Could this section be reused elsewhere?
- Is this section complex enough to warrant its own component?
Step 2: Look for Repetition
If you see similar elements repeated, that’s a strong candidate for a reusable component.
Step 3: Consider Data Requirements
Think about what data each component needs and where that data comes from.
Step 4: Plan the Component Hierarchy
Sketch out how your components will be nested and organized.
🔧 Try It Yourself!
Let’s practice creating components:
- Create a
UserCard
component that displays a user’s name and email 2. Create aProductCard
component that shows a product name and price 3. Use both components in your mainApp
component 4. Add some basic JavaScript logic like displaying the current time
Example Solution:
function UserCard() { const name = "John Doe"; const email = "john@example.com";
return ( <div className="user-card"> <h2>{name}</h2> <p>{email}</p> </div> );}
function ProductCard() { const name = "Laptop"; const price = 999.99;
return ( <div className="product-card"> <h2>{name}</h2> <p>${price}</p> </div> );}
function App() { return ( <div> <UserCard /> <ProductCard /> </div> );}
🧩 What You’ve Learned
- ✅ React components are the building blocks of React applications
- ✅ How to create components using JavaScript functions
- ✅ The two essential rules: components must return JSX and have one parent element
- ✅ How to use components in your application with JSX syntax
- ✅ The power of component reusability for reducing code duplication
- ✅ Adding JavaScript logic inside components for dynamic behavior
- ✅ Common mistakes to avoid when creating components
- ✅ How to think in components when designing user interfaces
🚀 What’s Next?
Great! You now understand what React components are and how to create them. In the next lesson, we’ll learn about React Component Types - understanding the different types of components and ways to create them.