Modern News Website in React
This is a modern React application that fetches the latest news articles using a public API (NewsAPI). It's built using React JS, functional components, and hooks like useState and useEffect to manage data fetching and component rendering.
News Fetching in React
In this example, we will fetch news articles from the News API. You will see how to display the articles dynamically in a clean and modern layout using React and Tailwind CSS.
React Code Example:
{`import React, { useState, useEffect } from 'react';
// Define the News component
function News() {
const [articles, setArticles] = useState([]); // State for storing articles
const [loading, setLoading] = useState(true); // State for loading indicator
const [error, setError] = useState(''); // State for error handling
// Fetch data when the component is mounted
useEffect(() => {
fetch('https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR_API_KEY')
.then((response) => response.json())
.then((data) => {
setArticles(data.articles); // Set the fetched articles in state
setLoading(false); // Stop loading
})
.catch((err) => {
setError('Failed to fetch news');
setLoading(false); // Stop loading
});
}, []); // Empty dependency array to run this effect only once when the component is mounted
// Handle loading and error states
if (loading) {
return Loading...
;
}
if (error) {
return {error}
;
}
// Render the list of news articles
return (
{articles.map((article, index) => (
))}
);
}
export default News;`}
Explanation:
In this code:
- useState is used to store the articles, loading status, and error messages in the component state.
- useEffect is used to fetch data from the News API when the component is mounted. This hook ensures that the data is fetched only once.
- The API call is made using fetch(), and the articles are stored in the state once fetched.
- The loading state is handled to show a loading message while the data is being fetched, and an error message is shown if the fetch fails.
- Each article is displayed with its title, description, and a link to the full article.
Setting Up News API:
To get started, you need to sign up for an API key from the NewsAPI website (NewsAPI.org) and replace the YOUR_API_KEY placeholder in the code with your actual API key.
Conclusion:
This simple React news app demonstrates how to fetch and display data from an external API. By using React hooks (useState, useEffect), we efficiently manage state and lifecycle methods in functional components. Tailwind CSS makes it easy to create a responsive, modern layout with minimal effort.