You’ve probably thought about making reusable components mainly because;

  • You hate rewriting code blocks
  • You want to work faster

Making a reusable component is pretty simple actually. Assuming you already have a react project created, go ahead and create your Card.js preferrably in your components directory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import React from "react";

const CardComponent = ({ header, body, footer }) => {
return (
<>
<div className="card">
<div className="card-header">{header}</div>
<div className="card-body">{body}</div>
<div className="card-footer">{footer}</div>
</div>
</>
);
};

export default CardComponent;

You must have noticed I’m using bootstrap classes, yeah I am. You can install bootstrap as well npm i --save bootstrap, then don’t forget to add import "bootstrap/dist/css/bootstrap.min.css"; to the very first component, prefferably index.js

So what we did is, we added a few props header, body, footer which are going to be passed down to the next component.

If I go to the App.js component or any other component, I’ll be able to reuse the Card.js by just;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React from "react";
import "./App.css";
import CardComponent from "./components/CardComponent";

function App() {
return (
<>
<Card
header="Card heading"
body="Card description"
footer="Footer information"
/>
</>
);
}

export default App;

That’s pretty much it.