📅  最后修改于: 2023-12-03 14:44:34.619000             🧑  作者: Mango
If you're looking to develop a mobile application that consumes news articles, the News API with React Native is a powerful combination for building applications that can display and filter news articles from all around the world.
News API is a simple and easy-to-use API that can quickly fetch news articles from over 30,000 sources worldwide. With News API, you can integrate news articles data into your application, enabling users to stay up-to-date with the latest news directly from your application.
React Native is an open-source mobile application framework created by Facebook that builds mobile applications using JavaScript and leverages React's declarative UI framework. With React Native, developers can create mobile applications for iOS and Android with a single codebase.
React Native is an efficient and streamlined framework that allows developers to reuse code across different platforms, thus saving development time and costs.
Using News API with React Native, you can retrieve and present live news from any source conveniently. There are several libraries and built-in components in React Native that you can use to build a visually appealing user interface.
Before proceeding, you must have Node.js installed on your machine.
npx react-native init MyNewsApp
cd MyNewsApp
npm install axios @react-native-async-storage/async-storage
To use News API, you will need to get an API key from newsapi.org.
Create a .env
file in the root directory and add your API key for News API.
API_KEY=your-api-key-here
src
folder and the necessary file structure as follows:src
├── components
│ └── Article.js
│
├── screens
│ ├── HomeScreen.js
│ └── ArticleScreen.js
│
└── utils
└── api.js
HomeScreen.js
- This screen will be responsible for fetching the news articles from News API and display them in a list format.import React from "react";
import { View, Text, StyleSheet, FlatList, TouchableOpacity } from "react-native";
import Article from "../components/Article";
import { getArticles } from "../utils/api";
class HomeScreen extends React.Component {
state = {
articles: [],
loading: true,
};
componentDidMount() {
this.fetchArticles();
}
fetchArticles = async () => {
try {
const articles = await getArticles();
this.setState({ articles, loading: false });
} catch (error) {
console.log(error.message);
this.setState({ loading: false });
}
};
navigateToArticle = (article) => {
this.props.navigation.navigate("Article", { article });
};
renderItem = ({ item }) => {
return (
<TouchableOpacity style={styles.articleContainer} onPress={() => this.navigateToArticle(item)}>
<Article {...item} />
</TouchableOpacity>
);
};
render() {
const { articles, loading } = this.state;
if (loading) {
return (
<View style={styles.container}>
<Text>Loading...</Text>
</View>
);
}
return (
<View style={styles.container}>
<FlatList
data={articles}
keyExtractor={(item) => item.title}
renderItem={this.renderItem}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
articleContainer: {
marginVertical: 10,
backgroundColor: "#fff",
padding: 10,
borderRadius: 10,
},
});
export default HomeScreen;
ArticleScreen.js
- This screen will display a single news article.import React from "react";
import { View, Text, StyleSheet, Image } from "react-native";
class ArticleScreen extends React.Component {
render() {
const { article } = this.props.route.params;
return (
<View style={styles.container}>
<Text style={styles.title}>{article.title}</Text>
<Image source={{ uri: article.urlToImage }} style={styles.image} />
<Text style={styles.description}>{article.description}</Text>
<Text style={styles.content}>{article.content}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "flex-start",
alignItems: "center",
padding: 10,
},
title: {
fontWeight: "bold",
fontSize: 20,
marginVertical: 10,
textAlign: "center",
},
image: {
width: "100%",
height: 200,
borderRadius: 10,
marginBottom: 10,
},
description: {
fontSize: 16,
fontStyle: "italic",
marginBottom: 10,
},
content: {
fontSize: 18,
lineHeight: 27,
textAlign: "justify",
},
});
export default ArticleScreen;
Article.js
- This component is responsible for rendering individual articles.import React from "react";
import { View, Text, StyleSheet, Image } from "react-native";
const Article = (props) => {
const { title, urlToImage, description } = props;
return (
<View style={styles.container}>
{urlToImage && <Image style={styles.image} source={{ uri: urlToImage }} />}
<Text style={styles.title}>{title}</Text>
<Text style={styles.description}>{description}</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "column",
justifyContent: "flex-start",
},
title: {
fontWeight: "bold",
fontSize: 18,
marginVertical: 5,
textAlign: "justify",
},
description: {
fontSize: 16,
textAlign: "justify",
},
image: {
width: "100%",
height: 200,
borderRadius: 10,
marginBottom: 5,
},
});
export default Article;
api.js
- This utility file will create an axios instance to fetch news articles.import axios from "axios";
import AsyncStorage from "@react-native-async-storage/async-storage";
const api = axios.create({
baseURL: "https://newsapi.org/v2",
timeout: 5000,
});
api.interceptors.request.use(
async (config) => {
const apiKey = await AsyncStorage.getItem("API_KEY");
config.params = {
...config.params,
apiKey,
};
return config;
},
(err) => {
return Promise.reject(err);
}
);
export const getArticles = async () => {
try {
const res = await api.get("/top-headlines", { params: { country: "us" } });
return res.data.articles;
} catch (error) {
throw error;
}
};
Using News API with React Native, you can quickly fetch and display news articles from all around the world in your mobile application. Utilizing the pre-built components and libraries, developers can create a beautiful and appealing user interface that can make the user experience better. Combining HTTP client libraries like Axios with AsyncStorage enables us to fetch and store critical information like an API key into our app with maximum security.
With proper configuration and careful attention to code structure and flow, News API and React Native can work together seamlessly and create delightful news applications that can provide timely information to users worldwide.