Breaking Our News App into Reusable Components ๐งฉ
As our News App grows, keeping everything inside a single component becomes messy and hard to
maintain.
That's where component structure comes in โ splitting the UI into small, reusable pieces.
In this tutorial, we will learn:
Why Break Into Components?
Instead of writing all our markup inside one big News component, we separate concerns:
Navbar handles the top navigation bar, News is the parent component that holds
the list
of articles in state, and NewsItem is a small, reusable component that displays a single
article card.
This makes the code easier to read, test, and reuse.
Step 1: Folder Structure
Organize your src folder like this.
src/
components/
Navbar.js
News.js
NewsItem.js
App.js
Step 2: Create the Navbar Component
The Navbar is a simple Function Component since it has no internal state.
import React from "react";
function Navbar() {
return (
<nav className="navbar navbar-dark bg-dark">
<div className="container-fluid">
<span className="navbar-brand mb-0 h1">๐ฐ News App</span>
</div>
</nav>
);
}
export default Navbar;
Step 3: Create the NewsItem Component
NewsItem is also a Function Component. It receives data through props and displays a
single news card.
import React from "react";
function NewsItem({ title, description, imageUrl, newsUrl }) {
return (
<div className="card my-3">
<img
src={imageUrl || "https://via.placeholder.com/600x300"}
className="card-img-top"
alt={title}
/>
<div className="card-body">
<h5 className="card-title">{title}</h5>
<p className="card-text">{description}</p>
<a href={newsUrl} target="_blank" rel="noreferrer" className="btn btn-sm btn-warning">
Read More
</a>
</div>
</div>
);
}
export default NewsItem;
Step 4: Update the News Component (Parent)
News stays a Class Component, since it holds the list of articles in
state
and maps over it to render a NewsItem for each one.
import React, { Component } from "react";
import NewsItem from "./NewsItem";
export class News extends Component {
state = {
articles: [
{
title: "React 19 Released",
description: "React 19 brings new improvements for developers.",
imageUrl: "",
newsUrl: "#",
},
{
title: "GitHub Pages Hosting Made Easy",
description: "Learn how to deploy your React app for free.",
imageUrl: "",
newsUrl: "#",
},
],
};
render() {
return (
<div className="container my-4">
<h2 className="text-center mb-4">Welcome to News App ๐ฐ</h2>
{this.state.articles.map((article, index) => (
<NewsItem
key={index}
title={article.title}
description={article.description}
imageUrl={article.imageUrl}
newsUrl={article.newsUrl}
/>
))}
</div>
);
}
}
export default News;
Step 5: Connect Everything in App.js
import React from "react";
import Navbar from "./components/Navbar";
import News from "./components/News";
function App() {
return (
<div>
<Navbar />
<News />
</div>
);
}
export default App;