TutorialsReactComponents
Share:

Components

beginner

Part of React Fundamentals

Theory

Components are the heart of React. They are reusable, self-contained building blocks that describe a part of the user interface. Everything in React is a component — from a simple button to an entire page.

Functional Components (Modern Approach)

There are two ways to define components in React: class components and functional components. Modern React (16.8+) strongly favors functional components with hooks.

A functional component is simply a JavaScript function that returns JSX:

function Greeting() {
  return <h1>Hello, World!</h1>
}

With arrow functions, you can write them more concisely:

const Greeting = () => <h1>Hello, World!</h1>

Functional components are simpler, easier to test, and use less code than class components.

Component Composition

Components can contain other components. This is called composition — one of React's core paradigms.

function Avatar() {
  return <img src="avatar.png" alt="User" />
}
 
function UserInfo() {
  return (
    <div className="user-info">
      <Avatar />
      <p>John Doe</p>
    </div>
  )
}

You can think of your UI as a component tree. At the top is the root App component, which renders children, which render their own children, and so on.

Importing and Exporting Components

To keep your code organized, you define each component in its own file and export it:

UserCard.jsx:

export default function UserCard() {
  return <div>User Card</div>
}

App.jsx:

import UserCard from './UserCard'
 
function App() {
  return (
    <div>
      <UserCard />
    </div>
  )
}

You can also use named exports:

export function Header() { ... }
export function Footer() { ... }

And import them with:

import { Header, Footer } from './Layout'

JSX Rules

JSX looks like HTML but has some important differences:

  1. Single root element: A component must return a single root element. You cannot return sibling elements directly.
// WRONG
return (
  <h1>Title</h1>
  <p>Paragraph</p>
)
 
// RIGHT
return (
  <div>
    <h1>Title</h1>
    <p>Paragraph</p>
  </div>
)
  1. All tags must be closed: Self-closing tags like <img> and <input> require a slash.
<img src="logo.png" alt="Logo" />
<input type="text" />
<br />
  1. className instead of class: Since class is a reserved word in JavaScript, JSX uses className.
<div className="container">Content</div>
  1. Curly braces for JavaScript: Use {} to embed JavaScript expressions.
<p>{user.name}</p>
<img src={imageUrl} alt={altText} />

Fragments

When you need to return multiple elements without adding an extra DOM node, use fragments:

return (
  <>
    <h1>Title</h1>
    <p>Paragraph</p>
  </>
)

The empty tag <> </> is shorthand for <React.Fragment>. Fragments do not create any actual DOM element.

Component Tree

A typical React app has a component tree like this:

App
├── Header
│   ├── Logo
│   └── Navigation
│       └── NavItem (repeated)
├── Main
│   ├── Sidebar
│   └── Content
│       └── Article
└── Footer

This hierarchical structure makes the code predictable and easy to reason about.

File Organization

A clean file structure is important. Common patterns include:

src/
├── components/
│   ├── Header.jsx
│   ├── Footer.jsx
│   └── Sidebar.jsx
├── pages/
│   ├── Home.jsx
│   ├── About.jsx
│   └── Contact.jsx
├── App.jsx
└── main.jsx

Keep each component in its own file. If a component gets too large (over 200 lines), consider breaking it into smaller sub-components.

Practical Examples

Example 1: Building a Profile Card with Composition
jsx
Example 2: Using Fragments to Group Elements
jsx

Fragments (<> </>) do not accept keys or attributes. If you need to pass a key prop, use the full <React.Fragment key={id}> syntax.

Exercises

Build a Button Component

easy

Create a reusable Button component that renders a button element with the text passed as children. The component should accept a className prop for styling.

Expected Output:

Two styled buttons rendered on the page with the given text

Fix Component Composition

medium

The following code has multiple JSX errors. Fix all issues: missing keys, incorrect attribute names, and sibling returns.

Expected Output:

A navigation component rendering two links wrapped in a nav element, no extra DOM nodes, with proper keys

Create a Card Layout

medium

Create a Card component that composes smaller sub-components: CardImage, CardContent, and CardActions. The Card should accept props for imageSrc, title, description, and a buttonText.

Expected Output:

A styled card with an image, title, description, and button

Mini Quiz

Mini Quiz

Mini Project

Mini Project: Blog Post Layout

Build a blog post page using component composition. Create reusable components for the blog header, author info, post content, comments section, and sidebar.

Requirements:

    Bonus Challenge

    Add a LikeButton component with state (counter) inside the blog post. Use the useState hook.