News app source code
Here is an example of a basic news app source code in React Native:
NewsApp.js
import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, ActivityIndicator } from 'react-native';
import axios from 'axios';
const NewsApp = () => {
const [news, setNews] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
axios.get('https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR_API_KEY')
.then(response => {
setNews(response.data.articles);
setLoading(false);
})
.catch(error => {
console.error(error);
});
}, []);
return (
<View>
{loading? (
<ActivityIndicator size="large" color="#0000ff" />
) : (
<FlatList
data={news}
renderItem={({ item }) => (
<View>
<Text>{item.title}</Text>
<Text>{item.description}</Text>
</View>
)}
keyExtractor={item => item.url}
/>
)}
</View>
);
};
export default NewsApp;
styles.js
import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
newsItem: {
padding: 20,
borderBottomWidth: 1,
borderBottomColor: '#ccc',
},
});
export default styles;
App.js
import React from 'react';
import { AppRegistry } from 'react-native';
import NewsApp from './NewsApp';
AppRegistry.registerComponent('NewsApp', () => NewsApp);
package.json
{
"name": "news-app",
"version": "0.0.1",
"dependencies": {
"axios": "^0.21.1",
"react": "17.0.2",
"react-native": "0.68.2",
"react-native-cli": "^2.0.1"
},
"scripts": {
"start": "react-native start",
"android": "react-native run-android",
"ios": "react-native run-ios"
}
}
Note: You need to replace YOUR_API_KEY
with your actual API key from newsapi.org.
This code uses the axios
library to make a GET request to the News API and retrieve the top headlines. The response is then stored in the news
state and displayed in a FlatList
component. The loading
state is used to display an activity indicator while the data is being fetched.
You can run the app using npm start
and then open it on a simulator or physical device.
This is just a basic example, and you can customize the app to fit your needs. You can add more features such as filtering, sorting, and searching, as well as customize the UI and layout.