How to create reusable components in React.js?

How to use Components in React.js?»

Now, you’ll see how to create reusable components instead. This is something that you’ll most likely use in all of your React projects.

There are five major steps that you need to follow to create a reusable component.

Step 1: Find the repeated portion of the JSX component

If you look at the component code present inside App() component, you’d notice that you’ve got three repeated sections of the code <div className=”row”></div>. It means that you can use one of these to create a reusable component.

Step 2: Give this block of code a meaningful name

This part of the code basically displays a news section. So, it’s logical it give it a name of NewsSection.

Step 3: Create a file with that name

Create a new file named NewsSection.js inside the src directory. Inside NewsSection.js, write the following code:

import React from 'react';

const NewsSection = () => {
return (
);
};

Inside return(), paste the copied component code (single component) as follows:

import React from 'react';
import faker from ‘faker’;

const NewsSection = () => {
return (
<div className="row">
<div className="col-md-8">
<div className="news-title">
<h2>Some news title here</h2>
</div>
<div className="publishdate">
<p>
May 12, 2019
</p>
</div>
<div className="news">
<p>
Lorem Ipsum ...
</p>
</div>
</div>
<div className="col-md-4">
<img alt="news" className="img-responsive" src={faker.image.city()} style={{width: '100%'}}/>
</div>
</div>
);
};

In this case you’re giving the same news title and news summary to all the reusable components. That is, if the component is used multiple times, it’ll show the same hard-coded data over and over again. But, that’s not practical; because all the news titles and summaries are going to be different in reality. That’s where props come into play. You’ll see how you can use props to fill unique data inside components.

Leave a Comment