How to Create Reusable Components in React

Think about this scenario, you are creating a blog app, and you need to create a list of articles, where each article is displayed using a card like this:

Blog article grid

These cards have the same style but contain different information. As you can imagine, if you hardcode everything, there will be a lot of repetitions.

So, what if you can isolate this card component, and reuse it when needed?

How to create a component

This is what the component system is designed for in React. It provides you with a way to modularize different parts of the application, breaking it into reusable pieces, and making your code cleaner and more maintainable.

To create a new component, first create a components directory inside the src folder if it doesn't already exist. Then, navigate to the components directory and create a new file named Card.jsx.

text
1.
2├── README.md
3├── index.html
4├── package-lock.json
5├── package.json
6├── public
7├── src
8│   ├── App.css
9│   ├── App.jsx
10│   ├── assets
11│   │   └── react.svg
12│   ├── components
13│   │   └── Card.jsx   <===
14│   ├── index.css
15│   └── main.jsx
16└── vite.config.js

src/components/Card.jsx

jsx
1function Card() {
2  return (
3    <div className="bg-white shadow-md rounded-lg overflow-hidden">
4      <img
5        src="https://via.placeholder.com/400x200"
6        alt="Article Image"
7        className="w-full h-48 object-cover"
8      />
9      <div className="p-6">
10        <h2 className="text-2xl font-bold mb-2">Article</h2>
11        <p className="text-gray-700 mb-4">Lorem ipsum dolor. . .</p>
12        <a href="#" className="text-blue-500 hover:text-blue-700">
13          Read more
14        </a>
15      </div>
16    </div>
17  );
18}
19
20export default Card;

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉