I am creating a UI for Coronavirus tracking. So I need a drop-down list to fetch data of different countries on clicking specific country.I am sharing the code segment.Any help would be appreciable.
import React from "react";
import Axios from "axios";
import { StyleSheet, View, ImageBackground, Text, Image, Picker } from "react-native";
import { Dropdown } from "react-native-material-dropdown";
export default class App extends React.Component {
constructor(props) {
super(props);
this.getCountryData = this.getCountryData.bind(this);
}
state = {
confirmed: 0,
recovered: 0,
deaths: 0,
countries: []
}
componentDidMount() {
this.getData();
}
async getData() {
const resApi = await Axios.get("https://covid19.mathdro.id/api");
const resCountries = await Axios.get("https://covid19.mathdro.id/api/countries");
const countries = [];
for (var i=0; i < resCountries.data.countries.length; i++) {
countries.push(resCountries.data.countries[i].name);
}
this.setState({
confirmed: resApi.data.confirmed.value,
recovered: resApi.data.recovered.value,
deaths: resApi.data.deaths.value,
countries
});
}
async getCountryData(event){
try {
const res = await Axios.get(`https://covid19.mathdro.id/api/countries/${event.target.value}`);
this.setState({
confirmed: res.data.confirmed.value,
recovered: res.data.recovered.value,
deaths: res.data.deaths.value
})}
catch (err) {
if(err.response.status === 404)
this.setState({
confirmed: "No data available",
recovered: "No data available",
deaths: "No data available"
})
}
}
renderCountryOptions() {
return this.state.countries.map((name, i) => {
return <Text key={name}>{name}</Text>
});
}
render() {
return (
<View style={styles.container}>
<View style={{justifyContent: 'center',alignItems: 'center'}}>
<View style={{height: 150, top:29,width:900, backgroundColor: 'steelblue'}} />
<Text style={styles.text}>COVID-19 Cases Overview</Text>
</View>
<Image
source={require("./assets/Covid-19.jpg")}
resizeMode="contain"
style={styles.image}
>
</Image>
<Text style={styles.text1}>Global Data</Text>
<View style={styles.dropDown}>
<Dropdown onChange={this.getCountryData}>
{this.renderCountryOptions()}
</Dropdown>
</View>
<View>
<View style={styles.boxConfirmed}>
<Text>Confirmed </Text>
<Text>{this.state.confirmed}</Text>
</View>
<View style={styles.boxRecovered}>
<Text>Recovered</Text>
<Text>{this.state.recovered}</Text>
</View>
<View style={styles.boxDeaths}>
<Text> Deaths</Text>
<Text>{this.state.deaths}</Text>
</View>
</View>
</View>
);
}
}
I am unable to extract data of individual country. Please suggest me how I can use Dropdown in React Native
You can use react native picker from react native community for the task...
<Picker
selectedValue={this.state.language}
style={{height: 50, width: 100}}
onValueChange={(itemValue, itemIndex) =>
this.setState({language: itemValue})
}>
this.state.list.map((val) => {
<Picker.Item label=val value=val />
})
Related
I am new to react native. I am writing the code in class component, I need a flatlist with checkbox that allow multiple select, add the selected data could be save in a array and pass to other screen. I have no idea about that.. Can anyone help??
Try this example:
import React, { Component } from 'react';
import { View, Text, Image, FlatList, TextInput } from 'react-native';
import { ListItem, Body } from 'native-base';
import CheckBox from '#react-native-community/checkbox';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
serachdata: [],
selectedId: []
};
}
componentDidMount(){
this.ApiCalling();
}
ApiCalling = () => {
const url = "YOUR_API"
fetch(url)
.then(res => res.json())
.then(res => {
this.setState({data: res.data})
this.setState({serachdata: res.data})
})
.catch(error => {
console.log("error ", error)
})
}
onCheckBoxPress = (id) => {
let checkboxes = this.state.selectedId;
if(checkboxes && checkboxes.includes(id)){
checkboxes.splice( checkboxes.indexOf(id), 1 );
} else {
checkboxes = checkboxes.concat(id);
}
this.setState({selectedId:checkboxes})
console.log("selectde checkbox id: ", checkboxes)
}
_filter = (text) => {
const newData = this.state.data.filter(item => {
const itemData = `${item.first_name.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
this.setState({serachdata:newData})
}
render(){
return(
<View style={{ marginTop: 50 }}>
<TextInput
autoCapitalize='none'
autoCorrect={false}
style={{ height: 40, borderColor: 'gray', borderWidth: 1, margin:10 }}
status='info'
placeholder='Search'
onChangeText={(text) => this._filter(text)}
textStyle={{ color: '#000' }}
/>
<FlatList
data={this.state.serachdata}
keyExtractor={(item, index) => String(index)}
renderItem={({item, index}) => {
return(
<ListItem key={index}>
<CheckBox
disabled={false}
value={this.state.selectedId && this.state.selectedId.includes(item.id)}
onChange={()=>this.onCheckBoxPress(item.id)}
/>
<Body>
<View style={{flexDirection:'row', justifyContent:'space-between'}}>
<Image source={{ uri: item.avatar }} style={{ height: 100, width: 100 }} />
<Text>{item.first_name}</Text>
<Text>{item.email}</Text>
{/* <Text>{item.name.last}</Text> */}
</View>
</Body>
</ListItem>)}}
/>
</View>
)
}
};
I am trying to display the zomato restaurant collection of a city on react native page. I am using zomato API. On zomato API documentation, I am using request URL given under "get zomato collections in a city"
Below is my code:
import React from 'react';
import { StyleSheet, Text, View, FlatList, Image, ActivityIndicator } from 'react-native';
import { Card, CardItem } from "native-base"
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: [],
}
}
getUserFromApi = () => {
return (
fetch("https://developers.zomato.com/api/v2.1/collections?city_id=1", {
headers: {
'Content-Type': 'application/json',
'user-key': '2bf4669cad5a8230fd2b220a2d4a37b9'
}
})
.then(response => response.json())
.then(responseJson => {
this.setState({
isLoading: false,
dataSource: responseJson.collections.collection
})
})
.catch(error => console.log(error))
)
}
componentDidMount() {
this.getUserFromApi();
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.progress}>
<ActivityIndicator
size="large"
color="#01CBC6"
/>
</View>
)
}
return (
<View style={{marginTop: 50}}>
<FlatList
data={this.state.dataSource}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<Card>
<CardItem>
<View style={styles.container}>
</View>
<View style={styles.userInfo}>
<Text> collections_id: {item.collections_id}</Text>
</View>
</CardItem>
<CardItem>
<View style={styles.container}>
</View>
<View style={styles.userInfo}>
<Text>title: {item.title}</Text>
</View>
</CardItem>
<CardItem>
<View style={styles.container}>
</View>
<View style={styles.userInfo}>
<Text>description: {item.description}</Text>
</View>
</CardItem>
</Card>
)}
/>
</View>
);
}
}
I am not getting any error, but my screen is blank. There is no output on my screen. I am not able to understand where in my code I am making mistake
//----------------set state like this 👇-----------------------//
this.setState({
isLoading: false,
dataSource: responseJson.collections,
});
//-------------------------------------☝-----------------------//
// Also look FlatList for how the data is rendered //
Working App : Expo Snack
import React from 'react';
import {
StyleSheet,
Text,
View,
FlatList,
Image,
ActivityIndicator,
} from 'react-native';
import { Card, CardItem } from 'native-base';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: [],
};
}
getUserFromApi = () => {
return fetch(
'https://developers.zomato.com/api/v2.1/collections?city_id=1',
{
headers: {
'Content-Type': 'application/json',
'user-key': '2bf4669cad5a8230fd2b220a2d4a37b9',
},
}
)
.then((response) => response.json())
.then((responseJson) => {
console.log('data:', responseJson);
//----------------set state like this------------------------//
this.setState({
isLoading: false,
dataSource: responseJson.collections,
});
//------------------------------------------------------------//
//Also look FlatList for how the data is rendered //
})
.catch((error) => console.log(error));
};
componentDidMount() {
this.getUserFromApi();
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.progress}>
<ActivityIndicator size="large" color="#01CBC6" />
</View>
);
}
return (
<View style={{ marginTop: 50 }}>
<FlatList
data={this.state.dataSource}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<Card>
<CardItem>
<View style={styles.container}></View>
<View style={styles.userInfo}>
{/**access data of for rendering like below 👇 */}
<Text> collections_id: {item.collection.collection_id}</Text>
</View>
</CardItem>
<CardItem>
<View style={styles.container}></View>
<View style={styles.userInfo}>
{/**access data of for rendering like below 👇 */}
<Text>title: {item.collection.title}</Text>
</View>
</CardItem>
<CardItem>
<View style={styles.container}></View>
<View style={styles.userInfo}>
{/**access data of for rendering like below 👇 */}
<Text>description: {item.collection.description}</Text>
</View>
</CardItem>
</Card>
)}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: { padding: 10 },
userInfo: { padding: 10 },
});
I am trying to retrieve data from an API (https://developers.zomato.com/documentation) and get title of restaurants and an image with it. However when I try to load an image I get a warning source.uri should not be an empty string.
Here is my code as it stands:
async componentDidMount() {
let id = this.props.navigation.state.params.category
let result;
try {
result = await axios.request({
method: 'get',
url: `https://developers.zomato.com/api/v2.1/search?category=${id}`,
headers: {
'Content-Type': 'application/json',
'user-key': "a31bd76da32396a27b6906bf0ca707a2",
},
})
} catch (err) {
err => console.log(err)
}
this.setState({
isLoading: false,
data: result.data.restaurants
})
}
render() {
return (
<View>
{
this.state.isLoading ?
<View style={{ flex: 1, padding: 20 }}>
<ActivityIndicator style={{color:'red'}} />
</View> :
(
this.state.data.length == 0 ?
<View style={{ flex: 1, padding: 20 }}>
<Text style={{ color: '#000', fontWeight: 'bold' }}>No restaurants from selected category</Text>
</View> :
<FlatList
style={{ marginBottom: 80 }}
keyExtractor={item => item.id}
data={this.state.data}
renderItem={({ item }) =>
<TouchableHighlight onPress={()=> console.log(item.restaurant.thumb)}>
<Card image={item.restaurant.thumb} style={styles.container}>
<Image resizeMode='contain' source={{ uri: item.restaurant.thumb }}/>
<Text style={{color:'#000',fontWeight:'bold'}}>{item.restaurant.name} </Text>
</Card>
</TouchableHighlight>
}
/>
)
}
</View>
);
}
as you can see when I touch the any of the cards I am console logging the link of the image uri and it shows up perfectly. Why is that when the app loads the images they are empty strings yet when I load it though console log the link shows up perfectly?
I am using axios to load my API
here is an expo snack link: https://snack.expo.io/r1XTaw4JU
So i got 2 issues, one is in the card component you were not providing the uri properly it should be image={{uri:item.restaurant.thumb}} and secondly for newyork your entity id must be
To search for 'Italian' restaurants in 'Manhattan, New York City',
set cuisines = 55, entity_id = 94741 and entity_type = zone
Its as per zomato docs,so do check out that. and find expo link : expo-snack
import React from 'react';
import {
View,
Text,
FlatList,
StyleSheet,
Button,
TouchableHighlight,
ActivityIndicator,
} from 'react-native';
import { createAppContainer } from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import { Card, Image } from 'react-native-elements';
import Constants from 'expo-constants';
import axios from 'axios';
export default class CategoryScreen extends React.Component {
constructor(props){
super(props);
this.state={
data : [],
isVisible: true,
city : '94741'
}
}
async componentDidMount() {
let id = "3"
let city = this.state.city
let result;
try {
result = await axios.request({
method: 'get',
url: `https://developers.zomato.com/api/v2.1/search?entity_id=${city}&entity_type=zone&category=${id}`,
headers: {
'Content-Type': 'application/json',
'user-key': "a31bd76da32396a27b6906bf0ca707a2",
},
})
} catch (err) {
err => console.log(err)
}
this.setState({
isLoading: false,
data: result.data.restaurants
})
console.log(result)
console.log(data)
}
render() {
return (
<View>
{
this.state.isLoading ?
<View style={{ flex: 1, padding: 20 }}>
<ActivityIndicator style={{color:'red'}} />
</View> :
(
this.state.data.length == 0 ?
<View style={{ flex: 1, padding: 20 }}>
<Text style={{ color: '#000', fontWeight: 'bold' }}>No restaurants from selected category</Text>
</View> :
<FlatList
style={{ marginBottom: 80 }}
keyExtractor={item => item.id}
data={this.state.data}
renderItem={({ item }) =>
<TouchableHighlight onPress={()=> alert(item.restaurant.location.city)}>
<Card image={{uri:item.restaurant.thumb}} style={styles.container}>
<Text style={{color:'#000',fontWeight:'bold'}}>{item.restaurant.name} </Text>
</Card>
</TouchableHighlight>
}
/>
)
}
</View>
);
}
};
const styles = StyleSheet.create({
});
I am developing an application where I have a button (TouchableHighlight) when pressing this button it is necessary to capture a screeshot of the current screen and save the file in the device.
My code does not show error, but when I press the button (TouchableHighlight) I get the message:
Image saved to file: ///data/user/0/com.appcamerav4/cache/ReactNative-snapshot-image8525057299267209213.jpg through Remote JS Debugging .
I can not open this directory and need to save the image to the device.
I'm new to react-native.
Follow my code below:
import React, { Component } from 'react';
import { Text, View, Image, StyleSheet, TouchableHighlight, WebView, StatusBar, Button } from 'react-native';
import { captureScreen } from "react-native-view-shot";
const zooMais = require('../imgs/zooMais.png');
const zooMenos = require('../imgs/zooMenos.png');
const imgScreeshot = require('../imgs/screeshot.png');
const btnZooMais = ()=>{
alert("Zoo Mais");
console.log("Zoom +");
}
const btnZooMenos = ()=>{
alert("Zoo Menos");
console.log("Zoom +");
}
const capitureScreen = ()=>{
captureScreen({
format: "jpg",
quality: 0.8,
}).then(
uri => console.log("Image saved to", uri),
error => console.error("Oops, snapshot failed", error)
);
}
export default class Monitor extends Component {
render() {
return (
<View style={ style.viewPrincipal }>
<StatusBar hidden />
<View style={ style.viewImagem } >
<WebView
style={style.video}
automaticallyAdjustContentInsets={true}
scalesPageToFit={true}
startInLoadingState={false}
contentInset={{top: 0, right: 0, left: 0, bottom: 0}}
scrollEnabled={true}
source={{uri: 'https://facebook.github.io/react/logo-og.png'}}
onNavigationStateChange = {this.handleNavigationStateChange}
/>
</View>
<View style={ style.viewRodape }>
<View style={style.viewMenu}>
<View >
<TouchableHighlight onPress={ btnZooMais } >
<Image style={style.imgMenu} source={zooMais } />
</TouchableHighlight>
</View>
<View>
<TouchableHighlight onPress={ capitureScreen }>
<Image style={style.imgMenu} source={ imgScreeshot } />
</TouchableHighlight >
</View>
<View>
<TouchableHighlight onPress={ btnZooMenos } >
<Image style={style.imgMenu} source={ zooMenos } />
</TouchableHighlight>
</View>
</View>
</View>
</View>
);
}
}
const style = StyleSheet.create({
viewPrincipal:{
flex: 1
},
viewImagem:{
flex:10,
justifyContent:'center',
alignItems:'stretch'
},
viewRodape:{
flex:1.3
},
viewMenu:{
flexDirection:'row',
justifyContent: 'space-between'
},
imgMenu:{
margin: 0,
marginBottom:0
},
video:{
flex:1
}
});
Make sure react-native-view-shot is correctly linked in XCode (might require a manual installation,
refer to React Native doc).
import React, { useRef } from "react"; // import useRef hook on top
const cardRef = useRef(); // Use this hook inside your func. component *important
// Define a function like this
const saveAsImage = async () => {
try {
const result = await captureRef(cardRef, {
result: "tmpfile",
quality: 1,
format: "png",
});
MediaLibrary.saveToLibraryAsync(result);
} catch (e) {
console.log(e);
}
};
Apply a prop eg. parentRef={cardRef} to your component, make sure the ref name matches which in this case is "cardRef".
Give any Button/TouchableOpacity
onPress={() => {saveAsImage();}}
To solve this problem you have to go on your App permission on your real mobile and allow for camera storage then you can easily save your ViewShot on Your Mobile.
go to App Permisssion in your App.info
allow Camera accesss storage
To save the screenshot to the camera roll, use this one: https://facebook.github.io/react-native/docs/cameraroll.html#savetocameraroll
More info: https://github.com/gre/react-native-view-shot Check the FAQ section
The Error has been resolved as per your guidelines.
But still can not take and save the screeshot of the desired ViewShot, where it has a react image.
I need to take and save the screeshot in the memory of my device.
Can you tell me if I'm on the right track or would I have another way to do it? Thanks!
Follow my current code.
import React, { Component } from 'react';
import { Text, View, Image, StyleSheet, TouchableHighlight } from 'react-native';
import { captureScreen } from "react-native-view-shot";
import ViewShot from "react-native-view-shot";
const zooMais = require('../imgs/zooMais.png');
const zooMenos = require('../imgs/zooMenos.png');
const imgScreeshot = require('../imgs/screeshot.png');
const btnZooMais = ()=>{
alert("Zoo Mais");
}
const btnZooMenos = ()=>{
alert("Zoo Menos");
}
const capitureScreen = ()=>{
captureScreen({
format: "jpg",
quality: 0.9,
}).then(
uri => console.log("Image saved to", uri),
error => console.error("Oops, snapshot failed", error)
);
}
export default class Monitor extends Component {
componentDidMount () {
this.refs.viewShot.capture().then(uri => {
console.log("do something with ", uri);
});
}
render() {
return (
<View>
<ViewShot ref="viewShot" options={{ format: "jpg", quality: 0.9 }} >
<Image source={{uri: 'https://facebook.github.io/react/logo-og.png'}} style={ style.video } />
</ViewShot>
<View style={style.menu}>
<View>
<TouchableHighlight onPress={ btnZooMais } >
<Image style={style.imgMenu} source={zooMais } />
</TouchableHighlight>
</View>
<View>
<TouchableHighlight onPress={ capitureScreen }>
<Image style={style.imgMenu} source={ imgScreeshot } />
</TouchableHighlight >
</View>
<View>
<TouchableHighlight onPress={ btnZooMenos } >
<Image style={style.imgMenu} source={ zooMenos } />
</TouchableHighlight>
</View>
</View>
</View>
);
}
}
const style = StyleSheet.create({
corpo: {
},
menu:{
flexDirection:'row',
justifyContent: 'space-between'
},
imgMenu:{
//margin: 15
},
video: {
width: 400,
height: 450
}
});
Looks like you may not have either linked the package or rebuilt the app after linking.
Try
$ react-native link react-native-view-shot
$ react-native run-{ios|android}