Menu

Building Reusable Components in React: Examples

Building Reusable Components

What Makes a Component Reusable?

Three things:

  1. It takes its data through props rather than hard-coding values.
  2. It does one job. A component that renders a card and fetches data and handles login is not reusable.
  3. It does not assume where it is used. Avoid baking in page-specific margins or headings.

Example: Refactoring Into a Reusable Component

Before: not reusable

jsx

function ReactCourseCard() {
  return (
    <div className="course-card">
      <h3>React Fundamentals</h3>
      <p>Beginner</p>
    </div>
  );
}

Every new course needs a new component file. That does not scale.

After: reusable

src/components/CourseCard.jsx

jsx

import ProgressBar from "./ProgressBar";

function CourseCard({ title, instructor, lessons, level = "Beginner", progress = 0 }) {
  return (
    <div className="course-card">
      <h3>{title}</h3>
      <p className="instructor">By {instructor}</p>
      <p>{lessons} lessons · {level}</p>
      <ProgressBar progress={progress} />
    </div>
  );
}

export default CourseCard;

src/components/ProgressBar.jsx

jsx

function ProgressBar({ progress }) {
  return (
    <div className="progress-track">
      <div className="progress-fill" style={{ width: `${progress}%` }}></div>
      <span>{progress}% complete</span>
    </div>
  );
}

export default ProgressBar;

How It Works

  • CourseCard no longer knows about any specific course. It renders whatever it is given.
  • ProgressBar receives progress as a prop from CourseCard, which received it from App. This chain of props is normal in React.
  • Defaults on level and progress mean the component still works if those props are missing.

File Organisation

A common beginner-friendly structure:

text

src/
├── components/
│   ├── Navbar.jsx
│   ├── CourseCard.jsx
│   └── ProgressBar.jsx
├── App.jsx
└── main.jsx

One component per file, named exactly like the component. As your app grows, group related components into subfolders.

Practice Task

Build a StudentProfile component that receives the following props and displays them:

  • name - the student's name
  • course - the course they are enrolled in
  • lessonsCompleted - a number
  • totalLessons - a number

Inside the component, calculate the completion percentage and pass it to the ProgressBar component you built above.

Then use StudentProfile three times in App.jsx with three different students.

Expected outcome: three profile blocks, each with its own name, course, and correctly filled progress bar.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details