enter image description here Iam new with react native,so maybe my question seems silly to all excepts.I want to add current time in text input.(i designd todo app,that show the todo list,now i want to show time in todo list,for eg i enter todo(complete frontend)and add,that contain complete and delete button,now i want to add time in that(task adding time).my code are following below,
import React from 'react';
import {
StyleSheet,
SafeAreaView,
View,
TextInput,
Text,
FlatList,
TouchableOpacity,
Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '#react-native-async-storage/async-storage';
const COLORS = {primary: '#1f145c', white: '#fff'};
const App = () => {
const \[todos, setTodos\] = React.useState(\[\]);
const \[textInput, setTextInput\] = React.useState('');
React.useEffect(() => {
getTodosFromUserDevice();
}, \[\]);
React.useEffect(() => {
saveTodoToUserDevice(todos);
}, \[todos\]);
const addTodo = () => {
if (textInput == '') {
Alert.alert('Error', 'Please input todo');
} else {
const newTodo = {
id: Math.random(),
task: textInput,
completed: false,
};
setTodos(\[...todos, newTodo\]);
setTextInput('');
}
};
const saveTodoToUserDevice = async todos => {
try {
const stringifyTodos = JSON.stringify(todos);
await AsyncStorage.setItem('todos', stringifyTodos);
} catch (error) {
console.log(error);
}
};
const getTodosFromUserDevice = async () => {
try {
const todos = await AsyncStorage.getItem('todos');
if (todos != null) {
setTodos(JSON.parse(todos));
}
} catch (error) {
console.log(error);
}
};
const markTodoComplete = todoId => {
const newTodosItem = todos.map(item => {
if (item.id == todoId) {
return {...item, completed: true};
}
return item;
});
setTodos(newTodosItem);
};
const deleteTodo = todoId => {
const newTodosItem = todos.filter(item => item.id != todoId);
setTodos(newTodosItem);
};
const clearAllTodos = () => {
Alert.alert('Confirm', 'Clear todos?', \[
{
text: 'Yes',
onPress: () => setTodos(\[\]),
},
{
text: 'No',
},
\]);
};
const ListItem = ({todo}) => {
return (
<View style={styles.listItem}>
<View style={{flex: 1}}>
<Text
style={{
fontWeight: 'bold',
fontSize: 20,
color: COLORS.primary,
textDecorationLine: todo?.completed ? 'line-through' : 'none',
}}>
{todo?.task}
</Text>
</View>
{!todo?.completed && (
<TouchableOpacity onPress={() => markTodoComplete(todo.id)}>
<View style={\[styles.actionIcon, {backgroundColor: 'green'}\]}>
<Icon name="done" size={20} color="white" />
</View>
</TouchableOpacity>
)}
<TouchableOpacity onPress={() => deleteTodo(todo.id)}>
<View style={styles.actionIcon}>
<Icon name="delete" size={20} color="white" />
</View>
</TouchableOpacity>
</View>
);
};
return (
<SafeAreaView
style={{
flex: 1,
backgroundColor: 'white',
}}>
<View style={styles.header}>
<Text
style={{
fontWeight: 'bold',
fontSize: 20,
color: COLORS.primary,
}}>
TODO APP
</Text>
<Icon name="delete" size={25} color="red" onPress={clearAllTodos} />
</View>
<FlatList
showsVerticalScrollIndicator={false}
contentContainerStyle={{padding: 20, paddingBottom: 100}}
data={todos}
renderItem={({item}) => <ListItem todo={item} />}
/>
<View style={styles.footer}>
<View style={styles.inputContainer}>
<TextInput
value={textInput}
placeholder="Add Todo"
onChangeText={text => setTextInput(text)}
/>
</View>
<TouchableOpacity onPress={addTodo}>
<View style={styles.iconContainer}>
<Icon name="add" color="white" size={30} />
</View>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
footer: {
position: 'absolute',
bottom: 0,
width: '100%',
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 20,
backgroundColor: COLORS.white,
},
inputContainer: {
height: 50,
paddingHorizontal: 20,
elevation: 40,
backgroundColor: COLORS.white,
flex: 1,
marginVertical: 20,
marginRight: 20,
borderRadius: 30,
},
iconContainer: {
height: 50,
width: 50,
backgroundColor: COLORS.primary,
elevation: 40,
borderRadius: 25,
justifyContent: 'center',
alignItems: 'center',
},
listItem: {
padding: 20,
backgroundColor: COLORS.white,
flexDirection: 'row',
elevation: 12,
borderRadius: 7,
marginVertical: 10,
},
actionIcon: {
height: 25,
width: 25,
backgroundColor: COLORS.white,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'red',
marginLeft: 5,
borderRadius: 3,
},
header: {
padding: 20,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
});
export default App;][1]
i got the answer ,answer is following below,
import React from 'react';
import {
StyleSheet,
SafeAreaView,
View,
TextInput,
Text,
FlatList,
TouchableOpacity,
Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '#react-native-async-storage/async-storage';
const COLORS = {primary: '#1f145c', white: '#fff'};
const App = () => {
const [todos, setTodos] = React.useState([]);
const [textInput, setTextInput] = React.useState('');
React.useEffect(() => {
getTodosFromUserDevice();
}, []);
React.useEffect(() => {
saveTodoToUserDevice(todos);
}, [todos]);
const addTodo = () => {
if (textInput == '') {
Alert.alert('Error', 'Please input todo');
} else {
const newTodo = {
id: Math.random(),
task: textInput,
completed: false,
time: getCurrentTime()
};
setTodos([...todos, newTodo]);
setTextInput('');
}
};
const saveTodoToUserDevice = async todos => {
try {
const stringifyTodos = JSON.stringify(todos);
await AsyncStorage.setItem('todos', stringifyTodos);
} catch (error) {
console.log(error);
}
};
const getTodosFromUserDevice = async () => {
try {
const todos = await AsyncStorage.getItem('todos');
if (todos != null) {
setTodos(JSON.parse(todos));
}
} catch (error) {
console.log(error);
}
};
***const getCurrentTime = () => {
let today = new Date();
let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
let time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
let dateTime = date + '/' + time;
return dateTime;
}***
const markTodoComplete = todoId => {
const newTodosItem = todos.map(item => {
if (item.id == todoId) {
return {...item, completed: true};
}
return item;
});
setTodos(newTodosItem);
};
const deleteTodo = todoId => {
const newTodosItem = todos.filter(item => item.id != todoId);
setTodos(newTodosItem);
};
const clearAllTodos = () => {
Alert.alert('Confirm', 'Clear todos?', [
{
text: 'Yes',
onPress: () => setTodos([]),
},
{
text: 'No',
},
]);
};
const comdel = () => {
Alert.alert('select status', 'Complete or Delete', [
{
text: 'Delete',
onPress: () => setTodos([]),
},
{
text: 'Complete',
onPress: () => {markTodoComplete(todo.id)}
},
]);
};
const ListItem = ({todo}) => {
return (
<View style={styles.listItem}>
<View style={{flex: 1}}>
<Text
style={{
fontWeight: 'bold',
fontSize: 20,
color: COLORS.primary,
textDecorationLine: todo?.completed ? 'line-through' : 'none',
}}>
{todo?.task}
</Text>
</View>
{/* {!todo?.completed && (
<TouchableOpacity onPress={() => markTodoComplete(todo.id)}>
<View style={[styles.actionIcon, {backgroundColor: 'green'}]}>
<Icon name="done" size={20} color="white" />
</View>
</TouchableOpacity>
)} */}
{/* <TouchableOpacity onPress={() => deleteTodo(todo.id)}>
<View style={styles.actionIcon}>
<Icon name="delete" size={20} color="white" />
</View>
</TouchableOpacity> */}
<View>
<Text>
{todo?.time}
</Text>
</View>
<Icon name="menu" size={40} color="#a9a9a9" onPress={comdel} />
</View>
);
};
return (
<SafeAreaView
style={{
flex: 1,
backgroundColor: 'white',
}}>
<View style={styles.header}>
<Text
style={{
fontWeight: 'bold',
fontSize: 20,
color: COLORS.primary,
}}>
TODO APP
</Text>
<Icon name="delete" size={25} color="red" onPress={comdel} />
</View>
<FlatList
showsVerticalScrollIndicator={false}
contentContainerStyle={{padding: 20, paddingBottom: 100}}
data={todos}
renderItem={({item}) => <ListItem todo={item} />}
/>
<View style={styles.footer}>
<View style={styles.inputContainer}>
<TextInput
value={textInput}
placeholder="Add Todo"
onChangeText={text => setTextInput(text)}
/>
</View>
<TouchableOpacity onPress={addTodo}>
<View style={styles.iconContainer}>
<Icon name="add" color="white" size={30} />
</View>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
footer: {
position: 'absolute',
bottom: 0,
width: '100%',
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 20,
backgroundColor: COLORS.white,
},
inputContainer: {
height: 50,
paddingHorizontal: 20,
elevation: 40,
backgroundColor: COLORS.white,
flex: 1,
marginVertical: 20,
marginRight: 20,
borderRadius: 30,
},
iconContainer: {
height: 50,
width: 50,
backgroundColor: COLORS.primary,
elevation: 40,
borderRadius: 25,
justifyContent: 'center',
alignItems: 'center',
},
listItem: {
padding: 40,
backgroundColor: "#d3d3d3",
flexDirection: 'column',
elevation: 12,
borderRadius: 7,
marginVertical: 10,
},
actionIcon: {
height: 25,
width: 25,
backgroundColor: COLORS.white,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'red',
marginLeft: 5,
borderRadius: 3,
},
header: {
padding: 20,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
});
export default App;
Related
I am working on react native from 3 months means I am still a beginner ,Help me with this Functionality : What I want is that when I add a product to my shopping cart the cart number on my bottom tab should increase at the same time . How can I achieve it?
This is my add to cart screen Here I am adding my products to the cart
import {
View, Text, StyleSheet, ScrollView, TouchableOpacity, Alert, Image, ActivityIndicator, Dimensions
} from 'react-native'
import React, { useEffect, useState } from 'react'
import Ionicons from 'react-native-vector-icons/Ionicons'
import Octicons from 'react-native-vector-icons/Octicons'
import AsyncStorage from '#react-native-async-storage/async-storage'
import AntDesign from 'react-native-vector-icons/AntDesign';
import ImageZoom from 'react-native-image-pan-zoom';
import { UserProvider } from './UserContext'
const AddProduct = ({ route, navigation }) => {
const [count, setCount] = useState(1)
console.log("this is item quantity=>", count);
const prodId = route.params.prodId
console.log('data is coming from route', prodId);
const [prodImg, setProdImg] = useState("")
console.log("this is product image from use state=>", prodImg);
const [productName, setProductName] = useState("")
const [productDesc, setProductDesc] = useState("")
// const [in_stock, setIn_stock] = useState("")
const [availableQty, setAvailableQty] = useState("")
const [basePrice, setBasePrice] = useState("")
const [variations, setVariations] = useState([])
console.log("this is variation data", variations);
const [changePrice, setChangePrice] = useState("")
const [variationid, setVariationid] = useState("")
console.log('this is variation id=>', variationid);
const [selectedVar, setselectedVar] = useState(0)
const [customerId, setCustomerId] = useState("")
console.log("This is customer id ", customerId);
const baseUrl = "https://team.flymingotech.in/azamDeals/public/"
const [loader, setLoader] = useState(false)
const GetProductById = () => {
setLoader(true)
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch(`https://team.flymingotech.in/azamDeals/public/api/readByID/${route.params.prodId}/read`, requestOptions)
.then(response => response.json())
.then(result => {
console.log(result)
setProdImg(result[0].data.product_images)
setProductName(result[0].data.product_name)
setProductDesc(result[0].data.product_desc)
setAvailableQty(result[0].data.available_qty)
setBasePrice(result[0].data.base_price)
// setProductData(result.data)
setVariations(result[0].data?.variations)
// if (result && result.data) {
// setVariations(result.data.variations);
// } else {
// console.log('Could not retrieve data');
// }
setLoader(false)
})
.catch(error => {
console.log('error in getProductbyId api', error)
setLoader(false)
});
}
const getId = async () => {
try {
const customer_id = JSON.parse(await AsyncStorage.getItem("Customer_id"))
console.log("this is getting async storage data", customer_id);
setCustomerId(customer_id)
} catch (error) {
console.log(error);
}
};
useEffect(() => {
getId()
GetProductById()
}, [route.params.prodId])
function increment() {
//setCount(prevCount => prevCount+=1);
setCount(function (prevCount) {
return (prevCount += 1);
});
}
function decrement() {
setCount(function (prevCount) {
if (prevCount > 0) {
return (prevCount -= 1);
} else {
return (prevCount = 0);
}
});
}
const AddCart = async () => {
if (variationid == 0) {
Alert.alert("Please select the product variation")
return false;
} else if (count == 0) {
Alert.alert("Qty cannot be 0")
}
else {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"product_id": prodId,
"item_qty": count,
"item_price": changePrice,
"total_price": "",
"c_id": customerId,
"variation_id": variationid
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
await fetch("https://team.flymingotech.in/azamDeals/public/api/new_cart", requestOptions)
.then(response => response.json())
.then(result => {
console.log(result)
if (result.status == 1) {
Alert.alert('Added to cart')
}
})
.catch(error => console.log('error', error));
}
}
const onSelect = (id) => {
setselectedVar(id)
console.log(id);
}
const images = [
{
url:
'https://raw.githubusercontent.com/AboutReact/sampleresource/master/sample_img.png',
},
{
url:
'https://raw.githubusercontent.com/AboutReact/sampleresource/master/old_logo.png',
},
];
return (
<View style={styles.mainContainer}>
<View style={{ height: 80, backgroundColor: '#006C32', flexDirection: 'row', paddingTop: 25 }}>
<TouchableOpacity onPress={() => navigation.goBack()}>
<AntDesign style={{ paddingLeft: 20 }} name='arrowleft' size={30} color="white" />
</TouchableOpacity>
<Text style={{ paddingLeft: 20, fontSize: 20, color: 'white' }}>Product Detail</Text>
</View>
{/* <SearchHeader /> */}
{loader ?
<View style={{
alignItems: "center",
justifyContent: "center",
height: "90%"
}}>
<ActivityIndicator size={50} color="green" />
</View>
:
<ScrollView>
<View style={{ marginLeft: 15, marginRight: 15 }}>
<View>
{/* <Image style={{ height: 300, width: '100%', borderRadius: 10, marginTop: 10 }}
source={{ uri: prodImg }} /> */}
<ImageZoom
cropWidth={350}
cropHeight={300}
imageWidth={200}
imageHeight={200}>
<Image style={{ width: 200, height: 200 }}
source={{ uri: prodImg }} />
</ImageZoom>
<Text style={{ color: 'black', fontWeight: 'bold', marginTop: 10 }}>{productName}</Text>
<Text style={{ color: 'black', backgroundColor: 'white' }}>{productDesc}</Text>
<Text style={{ color: 'black', backgroundColor: 'white' }} >Stock:{availableQty}</Text>
<Text style={{ color: 'black', backgroundColor: 'white' }} >Base Price:₹{basePrice}</Text>
<Text style={{ color: 'black', backgroundColor: 'white' }} >Variation Price:₹{changePrice}</Text>
{/* <Text style={{ color: 'black', backgroundColor: 'white' }} >Variationid:{variationid}</Text> */}
<View style={{ marginTop: 14 }}>
<Text style={{ color: 'black', fontSize: 18, }}>Size</Text>
<View style={{
flexDirection: 'row',
justifyContent: 'space-around', height: 25
}}>
{/* {console.log("type", productData.variations.length)} */}
<View >
{variations?.length > 0 && variations.map((item, i) => (
<View key={i}>
<TouchableOpacity onPress={() => setChangePrice(item.variation_price,) | setVariationid(item.id) |onSelect(item.id)} style={{
height: 70, width: 120,
borderWidth: 0.5, borderColor: 'grey', borderRadius: 10,
justifyContent: 'center', alignItems: 'center',
backgroundColor: selectedVar === item.id ? "lightgrey" : "#fff"
}}>
<Text style={{ color: 'black', }}>{item.variation_label}</Text>
<Text style={{ color: 'black', }}>{item.variation_weight}</Text>
</TouchableOpacity>
</View>
))}
</View>
{/* <FlatList horizontal
data={productData}
renderItem={(item)=>renderItem(item)}
/> */}
{/* <Pressable onPress={() => getSize('s')} style={[styles.variable, { backgroundColor: size === 's' ? '#D1D1D1' : '#FFF' }]}><Text style={styles.variableValue}>S</Text></Pressable>
<Pressable onPress={() => getSize('m')} style={[styles.variable, { backgroundColor: size === 'm' ? '#D1D1D1' : '#FFF' }]}><Text style={styles.variableValue}>M</Text></Pressable>
<Pressable onPress={() => getSize('l')} style={[styles.variable, { backgroundColor: size === 'l' ? '#D1D1D1' : '#FFF' }]}><Text style={styles.variableValue}>L</Text></Pressable> */}
</View>
</View>
<View style={{ flexDirection: "row", marginTop: 50, justifyContent: 'space-between', paddingBottom: 10 }}>
<View style={styles.countButton}>
<TouchableOpacity onPress={decrement} style={{ alignSelf: 'center', marginLeft: 5 }}>
<Octicons name="dash" size={28} color="black" />
</TouchableOpacity>
<Text style={{ alignSelf: 'center', fontSize: 17, marginLeft: 4, color: 'black' }}>{count}</Text>
<TouchableOpacity onPress={increment} style={{ alignSelf: 'center' }}>
<Ionicons name="add" size={28} color="black" />
</TouchableOpacity>
</View>
<TouchableOpacity onPress={AddCart} style={{
backgroundColor: '#006C32', height: 40
, justifyContent: 'center', alignItems: 'center', width: 150, borderRadius: 5,
}}>
<Text style={{ color: 'white', fontWeight: 'bold' }}>Add to Cart</Text>
</TouchableOpacity>
</View>
{/* <View>
<TouchableOpacity style={{
width: 300, marginTop: 20, backgroundColor: 'darkgreen', height: 50
, borderRadius: 10, justifyContent: 'center', alignItems: 'center', alignSelf: 'center'
}}>
<Text style={{ color: 'white', fontWeight: 'bold' }}>Buy Now</Text>
</TouchableOpacity>
</View> */}
</View>
</View>
</ScrollView>
}
</View>
)
}
const styles = StyleSheet.create({
mainContainer: {
flex: 1,
backgroundColor: 'white'
},
image: {
height: 300, width: '100%',
},
countButton: {
backgroundColor: 'white', height: 40, borderWidth: 0.5, borderColor: 'grey'
, width: 100, flexDirection: 'row', borderRadius: 10, justifyContent: 'space-between',
},
variable: {
padding: 5,
color: 'black',
borderWidth: 1,
borderColor: '#999999',
borderRadius: 4,
},
variableValue: {
fontWeight: '700',
},
})
export default AddProduct
And this is my screen where I am showing the count of the products as a badge using an API it is working it is showing the data but when I refresh the app that time only it shows the count
import { View, Text, StyleSheet } from 'react-native'
import React, { useEffect, useState } from 'react'
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import { getFocusedRouteNameFromRoute } from '#react-navigation/native';
import Ionicons from 'react-native-vector-icons/Ionicons'
import User from 'react-native-vector-icons/FontAwesome'
// screens
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack'
import Home from '../screens/HomeScreen/Home';
import { CustomerStack, Cart, Profile } from './CustomerStack';
import { Badge } from 'react-native-elements';
import AsyncStorage from '#react-native-async-storage/async-storage';
// Screen Names
const Stack = createNativeStackNavigator();
const Tab = createBottomTabNavigator();
const BottomTabNav = ({ route, navigation }) => {
const [Count, setCount] = useState("")
console.log("this is Count of cart=>",Count);
useEffect(() => {
getCartCount()
}, [])
const getCartCount = async () => {
const customer_id = JSON.parse(await AsyncStorage.getItem("Customer_id"))
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch(`https://team.flymingotech.in/azamDeals/public/api/countCartItems/${customer_id}`, requestOptions)
.then(response => response.json())
.then(result => {
console.log(result)
setCount(result.data)
})
.catch(error => console.log('error', error));
}
<Tab.Screen
name="CustomerStack"
component={CustomerStack}
options={({ route }) => ({ tabBarStyle: getTabBarStyle(route) })} />
const getTabBarStyle = (route) => {
const routeName = getFocusedRouteNameFromRoute(route) ?? 'CustomerStack';
let display = (routeName === 'Player') ? 'none' : 'flex';
return { display }
}
return (
<Tab.Navigator initialRouteName='CustomerStack'
tabBarOptions={{
// activeTintColor: 'red',
inactiveTintColor: 'white',
}}
screenOptions={({ route, }) => ({
tabBarStyle: {
backgroundColor: '#006C32',
},
tabBarIcon: ({ focused, color, size }) => {
let iconName;
let rn = route.name;
if (rn === "CustomDrawer") {
iconName = focused ? 'home' : 'home'
}
else if (rn === "CustomerStack") {
iconName = focused ? 'home' : 'home'
}
else if (rn === "Cart") {
<View style={styles.unreadBadge}>
<Text style={styles.unreadBadgeText}>11</Text>
</View>
iconName = focused ? 'shopping-cart' : 'shopping-cart'
} else if (rn === "Account") {
iconName = focused ? 'user' : 'user'
}
return <User name={iconName} size={size} color={color} />
},
})}>
<Tab.Screen options={{ headerShown: false, tabBarActiveTintColor: 'white', }} name="CustomerStack" component={CustomerStack} />
<Tab.Screen options={{
headerShown: false, tabBarActiveTintColor: 'white',
tabBarBadge: Count
}} name="Cart" component={Cart} />
<Tab.Screen options={{ headerShown: false, tabBarActiveTintColor: 'white', }} name="Account" component={Profile} />
</Tab.Navigator>
)
}
const styles = StyleSheet.create({
unreadBadge: {
backgroundColor: '#FF3250',
position: 'absolute',
left: 20,
bottom: 18,
width: 25,
height: 18,
borderradius: 25,
alignItems: 'center',
justifyContent: 'center',
zIndex: 100, // this one is used to put message notify on top of icon
},
unreadBadgeText: {
color: 'white',
fontWeight: '600',
},
})
export default BottomTabNav
What I was going to try is that keep calling that API every 5 seconds then after calling the API So many times it will give Too many request error .
Whether I should use UseContext or Pass data through both the screen and call API I don't get it!
Here I have created toggle custom checkboxes and those are rendered within FlatList with Name.
Now which checkboxes are checked i want to send those names into next screen using navigation.
So how can i implement that functionality, if anyone knows then please help me for the same.
/**Code For custom checkbox:**/
import React from "react";
import {
TouchableOpacity,
Image,
View,
SafeAreaView,
Text,
} from "react-native";
import { useState } from "react";
import IconAntDesign from "react-native-vector-icons/AntDesign";
export function CheckBoxCustom() {
const [count, setCount] = useState(0);
return (
<SafeAreaView>
<TouchableOpacity
style={{
backgroundColor: "white",
width: 20,
height: 20,
borderWidth: 2,
borderColor: "#ddd",
}}
onPress={() => setCount(!count)}
>
{count ? (
<IconAntDesign name="check" size={15} color={"black"} />
) : null}
</TouchableOpacity>
</SafeAreaView>
);
}
/**Code for FlatList:**/
import React, {useState} from 'react';
import {
SafeAreaView,
Text,
View,
TouchableOpacity,
Image,
StyleSheet,
FlatList,
Dimensions,
useWindowDimensions,
ScrollView,
Button,
} from 'react-native';
import Header from '../CustomComponents/RestaurentUI/Header';
import {CheckBoxCustom} from '../CustomComponents/RestaurentUI/Checkbox';
import {TextInput} from 'react-native-gesture-handler';
import {TabView, SceneMap, TabBar} from 'react-native-tab-view';
import {NavigationContainer, useNavigation} from '#react-navigation/native';
import GetCheckBoxData from './GetCheckBoxData';
const data = [
{
name: 'Lumlère brûlée',
status: 'Problems',
},
{
name: 'Aucune eau chaude',
status: 'Problems',
},
{
name: 'Lumlère brûlée',
status: 'Problems',
},
{
name: 'Service de ménage',
status: 'Problems',
},
{
name: 'AC non-fonctionnel',
status: 'Problems',
},
{
name: 'WIFI non-fonctionnel',
status: 'Problems',
},
{
name: 'Four non-fonctionnel',
status: 'Problems',
},
];
const renderItem = ({item, index}) => {
return (
<View>
<View style={{flexDirection: 'row'}}>
<CheckBoxCustom />
<Text style={{marginLeft: 10}}>{item.name} </Text>
</View>
</View>
);
};
const separator = () => {
return (
<View
style={{
height: 1,
backgroundColor: '#f1f1f1',
marginBottom: 12,
marginTop: 12,
}}
/>
);
};
const FirstRoute = () => (
<FlatList
style={{marginTop: 20}}
data={data}
keyExtractor={(e, i) => i.toString()}
renderItem={renderItem}
ItemSeparatorComponent={separator}
/>
);
const SecondRoute = () => (
<View style={[styles.scene, {backgroundColor: 'white'}]} />
);
const initialLayout = {width: Dimensions.get('window').width};
const renderScene = SceneMap({
first: FirstRoute,
second: SecondRoute,
});
const ReportScreen = ({navigation}) => {
const nav = useNavigation();
const layout = useWindowDimensions();
const [index, setIndex] = useState(0);
const [routes] = useState([
{key: 'first', title: 'Problemes'},
{key: 'second', title: 'Besoins complémentaitaires'},
]);
const goToScreen = () => {
navigation.navigate('GetCheckBoxData', {title: 'Hii all'});
};
const [checked, setChecked] = useState({});
const checkToggle = id => {
setChecked(checked => ({
...checked,
[id]: !checked[id],
}));
};
return (
<SafeAreaView style={styles.safearea}>
<Header title="Report" />
<ScrollView showsVerticalScrollIndicator={false} bounces={false}>
<View style={{flexDirection: 'row', marginTop: 20}}>
<View style={{flex: 1, height: 1, backgroundColor: '#ccc'}} />
</View>
<View style={styles.cardView}>
<View style={styles.subView}>
<Image
style={styles.image}
source={require('../Assets/UIPracticeImage/H1.jpg')}
/>
<View style={styles.internalSubView}>
<View style={styles.nameView}>
<Text style={styles.nameText}>Pine Hill Green Caban</Text>
</View>
<View style={styles.dateView}>
<Text style={styles.dateText}>May 22-27</Text>
</View>
</View>
</View>
</View>
<View style={{flexDirection: 'row'}}>
<View style={{flex: 1, height: 1, backgroundColor: '#ccc'}} />
</View>
<View
style={{
// backgroundColor: 'lime',
flex: 1,
height: 385,
width: '100%',
}}>
<TabView
navigationState={{index, routes}}
renderScene={renderScene}
onIndexChange={setIndex}
initialLayout={initialLayout}
style={styles.container}
renderTabBar={props => (
<TabBar
tabStyle={{alignItems: 'flex-start', width: 'auto'}}
{...props}
renderLabel={({route, color}) => (
<Text style={{color: 'black'}}>{route.title}</Text>
)}
style={{backgroundColor: 'white'}}
/>
)}
/>
</View>
<Button title="Click me" onPress={goToScreen} />
</ScrollView>
</SafeAreaView>
);
};
export default ReportScreen;
const styles = StyleSheet.create({
safearea: {
marginHorizontal: 20,
},
cardView: {
borderRadius: 10,
marginVertical: 10,
paddingVertical: 8,
},
subView: {
flexDirection: 'row',
},
image: {
height: 80,
width: 110,
borderRadius: 10,
},
internalSubView: {
justifyContent: 'space-between',
flex: 1,
},
nameView: {
justifyContent: 'space-between',
flexDirection: 'row',
alignItems: 'center',
marginLeft: 10,
},
nameText: {
fontWeight: 'bold',
width: '45%',
fontSize: 15,
},
dateView: {
flexDirection: 'row',
alignItems: 'center',
marginLeft: 10,
justifyContent: 'space-between',
},
dateText: {
width: 80,
},
listTab: {
flexDirection: 'row',
marginBottom: 20,
marginTop: 20,
},
btnTab: {
borderWidth: 3,
borderColor: 'white',
flexDirection: 'row',
marginRight: 10,
},
btnTabActive: {
borderWidth: 3,
borderBottomColor: '#fdd83d',
borderColor: 'white',
},
scheduleButton: {
backgroundColor: '#fdd83d',
alignItems: 'center',
paddingVertical: 15,
borderRadius: 10,
marginTop: 15,
},
container: {
marginTop: 20,
},
scene: {
flex: 1,
},
});
[![UI image][1]][1]
[1]: https://i.stack.imgur.com/AuLT8.png
You may want to lift the checkbox state to the parent component, i.e. make the checkboxes controlled, and collect the checked checkbox values. For this I'm assuming your data items have an id property, but any unique item property will suffice.
Example:
export function CheckBoxCustom({ checked, onPress }) {
return (
<SafeAreaView>
<TouchableOpacity
style={{
backgroundColor: "white",
width: 20,
height: 20,
borderWidth: 2,
borderColor: "#ddd",
}}
onPress={onPress}
>
{checked ?? <IconAntDesign name="check" size={15} color={"black"} />}
</TouchableOpacity>
</SafeAreaView>
);
}
...
const [checked, setChecked] = useState({});
const checkToggle = id => {
setChecked(checked => ({
...checked,
[id]: !checked[id],
}));
};
const renderItem = ({ item, index }) => {
return (
<View>
<View style={{ flexDirection: "row" }}>
<CheckBoxCustom
checked={checked[item.id]}
onPress={() => checkToggle(item.id)}
/>
<Text style={{ marginLeft: 10 }}>{item.name}</Text>
</View>
</View>
);
};
<FlatList
data={dataList}
keyExtractor={(e, i) => i.toString()}
renderItem={renderItem}
ItemSeparatorComponent={separator}
/>;
If your data hasn't any good GUID candidates then I suggest augmenting your data to include good GUIDs.
To pass the checked/selected items filter the dataList array.
Example:
const selected = dataList.filter(
item => checked[item.id]
);
// pass selected in navigation action
Here is my screen component with two textinputs from the link. I have removed some other code that isn't necessary to this issue.
When i choose the date from the popup it appears in the text input but doesnt get validated.
I cannot use the result of DatePicker component as it is , so i am doing some formating and saved to a function getDate.
How would you go about implemnting this ? is there any better way
enter image description here
import React, { useState, useContext, useEffect } from 'react';
import {
StyleSheet,
View,
Text,
TextInput,
TouchableOpacity,
ScrollView,
KeyboardAvoidingView,
Platform,
Image,
} from 'react-native';
import { icons, COLORS, } from '../constants';
import { Formik } from 'formik';
import * as yup from "yup";
import client from '../api/client';
import DateTimePickerModal from "react-native-modal-datetime-picker";
const addfarm = ({ navigation, Arrival_Date }) => {
const addFarmValidationSchema = yup.object().shape({
Farm_Code: yup.string().required('Please Enter the chick price'),
Arrival_Date: yup.string().required('Please Choose a date'),
});
const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
const [date, setDate] = useState('');
const showDatePicker = () => {
setDatePickerVisibility(true);
};
const hideDatePicker = () => {
setDatePickerVisibility(false);
};
const handleConfirm = (date) => {
hideDatePicker();
setDate(date);
};
const getDate = () => {
let tempDate = JSON.stringify(date).split(/[ ",T,]/);
return date !== ''
? `${tempDate[1]}`
: '';
};
const newDate = getDate();
const addFarmInfo = {
Farm_Code: '',
Arrival_Date: '',
};
const add = async (values) => {
const res = await client({
method: 'POST',
url: '/Farm/SaveFarm',
data: JSON.stringify({ ...values, id })
})
.then(res => console.log(res.data))
.catch(err => console.log(err))
}
return (
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : null}
style={{ flex: 1 }}>
<ScrollView style={styles.container}>
<Formik
initialValues={addFarmInfo}
validateOnMount={true}
onSubmit={add}
validationSchema={addFarmValidationSchema}>
{({
handleChange,
handleBlur,
handleSubmit,
values,
touched,
errors,
isValid,
setFieldValue,
}) => {
const {
Farm_Code,
Arrival_Date,
} = values
return (
<View
style={{
paddingHorizontal: '10%',
paddingTop: 50,
marginTop: 50,
backgroundColor: COLORS.main_background,
}}>
<Text style={styles.auth_text}>Add Farm</Text>
<Text style={styles.tag}>
Farm Code:
</Text>
<View
style={[styles.textInputView, { marginBottom: 10 }]}>
<TextInput
onChangeText={handleChange('Farm_Code')}
onBlur={handleBlur('Farm_Code')}
value={Farm_Code}
placeholder="Farm Code"
placeholderTextColor={COLORS.placeholder_fonts}
selectionColor={COLORS.drawer_button}
style={styles.textInput}
/>
<Image
source={!errors.Farm_Code ? icons.tick : icons.close}
resizeMode="stretch"
style={{
width: 18,
height: 18,
tintColor: !errors.Farm_Code ? COLORS.drawer_button : 'red',
alignItems: 'center',
marginRight: 10,
}}
/>
</View>
{(errors.Farm_Code && touched.Farm_Code) &&
<Text style={styles.errors}>{errors.Farm_Code}</Text>
}
<Text style={styles.tag}>
Arrival Date:
</Text>
<View
style={[styles.textInputView, { marginBottom: 10 }]}>
<TextInput
onChangeText={handleChange('Arrival_Date')}
onBlur={handleBlur('Arrival_Date')}
value={newDate}
onFocus={showDatePicker}
placeholder="yyyy/mm/dd"
placeholderTextColor={COLORS.placeholder_fonts}
selectionColor={COLORS.drawer_button}
style={styles.textInput}
/>
<TouchableOpacity style={{ marginRight: 10, }}
onPress={showDatePicker}
>
<DateTimePickerModal
isVisible={isDatePickerVisible}
mode="date"
onConfirm={handleConfirm}
onCancel={hideDatePicker}
/>
<Image
source={icons.calendar}
resizeMode="stretch"
style={{
width: 18,
height: 18,
tintColor: COLORS.secondary_fonts,
alignItems: 'center'
}}
/>
</TouchableOpacity>
<Image
source={!errors.Arrival_Date ? icons.tick : icons.close}
resizeMode="stretch"
style={{
width: 18,
height: 18,
tintColor: !errors.Arrival_Date ? COLORS.drawer_button : 'red',
alignItems: 'center',
marginRight: 10,
}}
/>
</View>
{(errors.Arrival_Date && touched.Arrival_Date) &&
<Text style={styles.errors}>{errors.Arrival_Date}</Text>
}
{(errors.Arrival_Date && touched.Arrival_Date) &&
<Text style={styles.errors}>{errors.Arrival_Date}</Text>
}
{/* Save */}
<TouchableOpacity
disabled={!isValid}
onPress={handleSubmit}
style={[styles.button, { backgroundColor: isValid ? COLORS.authButtons : COLORS.placeholder_fonts, marginTop: 10 }]}>
<Text style={styles.button_Text}>Save</Text>
</TouchableOpacity>
</View>
)
}
}
</Formik >
</ScrollView>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: COLORS.main_background,
},
textInput: {
flex: 1,
paddingLeft: 10,
color: 'black',
},
auth_text: {
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 5,
},
button: {
height: 50,
width: '100%',
marginVertical: 20,
borderRadius: 10,
alignItems: 'center',
justifyContent: 'center',
},
button_Text: {
fontSize: 18,
color: COLORS.white,
},
login_nav: {
fontSize: 12,
textAlign: 'center',
fontWeight: '400',
marginTop: 10,
},
errors: {
fontSize: 14,
color: 'red',
fontWeight: '400',
marginTop: 5,
},
textInputView: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
borderWidth: 1,
borderRadius: 10,
height: 50,
width: '100%',
borderColor: COLORS.secondary_fonts,
},
tag: {
color: 'black',
fontSize: 15,
marginBottom: 4,
marginLeft: 4
},
});
export default addfarm;
If you want formik to handle the validation, you should call the setFieldValue method and it will trigger the validation as the documentation says
Problem:
I have created react native camera but it is looked like this.
But the problem is the background color of camera action icons are transparent.
This is my code.
import React, {useState, useEffect} from 'react';
import {
AppRegistry,
StyleSheet,
TouchableOpacity,
View,
Image,
CameraRoll,
Platform,
} from 'react-native';
import IoniconsIcon from 'react-native-vector-icons/Ionicons';
import EntypoIcon from 'react-native-vector-icons/Entypo';
import AppText from '_components/appText';
import {RNCamera} from 'react-native-camera';
import normalize from '_utils/fontsize';
let countRecordTime;
const PendingView = () => (
<View
style={{
flex: 1,
backgroundColor: 'lightgreen',
justifyContent: 'center',
alignItems: 'center',
}}>
<AppText>Waiting</AppText>
</View>
);
const takePicture = async (camera) => {
const options = {quality: 1};
const data = await camera.takePictureAsync(options);
console.log(data.uri);
};
const recordVideo = async (
camera,
recording,
seconds,
setRecording,
setSeconds,
) => {
if (camera) {
if (!recording) {
startRecording(recording, setRecording, seconds, setSeconds, camera);
} else {
stopRecording(camera, setSeconds);
}
}
};
const startRecording = async (
recording,
setRecording,
seconds,
setSeconds,
camera,
) => {
setRecording(true);
console.log('>>>>>> start recording seconds', seconds);
const cameraConfig = {maxDuration: 20};
const data = await camera.recordAsync(cameraConfig);
console.log('>>>>>> data', data);
setRecording(false);
};
const stopRecording = (camera, setSeconds) => {
camera.stopRecording();
setSeconds(0);
};
const secondsToMMSS = (seconds) => {
console.log('>>>>>> seconds', seconds);
let m = Math.floor(seconds / 60);
let s = Math.floor(seconds % 60);
let mDisplay = m < 10 ? `0${m}` : `${m}`;
let sDisplay = s < 10 ? `0${s}` : `${s}`;
return `${mDisplay}:${sDisplay}`;
};
const VideoRecording = (props) => {
const [type, setType] = useState(RNCamera.Constants.Type.back);
const [flashMode, setFlashMode] = useState(RNCamera.Constants.FlashMode.off);
const [recording, setRecording] = useState(false);
const [seconds, setSeconds] = useState(0);
useEffect(() => {
if (recording) {
countRecordTime = setInterval(() => setSeconds(seconds + 1), 1000);
}
if (!recording && countRecordTime) {
clearInterval(countRecordTime);
}
if (seconds === 20 && countRecordTime) {
clearInterval(countRecordTime);
setRecording(false);
}
return () => {
if (countRecordTime) {
clearInterval(countRecordTime);
}
};
}, [recording, seconds]);
return (
<View style={styles.container}>
<RNCamera
style={styles.preview}
autoFocus={RNCamera.Constants.AutoFocus.on}
type={type}
flashMode={flashMode}
faceDetectionMode={RNCamera.Constants.FaceDetection.Mode.fast}
ratio="4:3"
whiteBalance={RNCamera.Constants.WhiteBalance.auto}
captureAudio={true}
androidCameraPermissionOptions={{
title: 'Permission to use camera',
message: 'We need your permission to use your camera',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}
androidRecordAudioPermissionOptions={{
title: 'Permission to use audio recording',
message: 'We need your permission to use your audio',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}>
{({camera, status, recordAudioPermissionStatus}) => {
if (status !== 'READY') {
return <PendingView />;
}
return (
<>
<View
style={{
flex: 0,
flexDirection: 'row',
justifyContent: 'center',
}}>
<TouchableOpacity
style={styles.capture}
onPress={(_) => {
switch (flashMode) {
case RNCamera.Constants.FlashMode.off:
setFlashMode(RNCamera.Constants.FlashMode.auto);
break;
case RNCamera.Constants.FlashMode.auto:
setFlashMode(RNCamera.Constants.FlashMode.on);
break;
case RNCamera.Constants.FlashMode.on:
setFlashMode(RNCamera.Constants.FlashMode.off);
break;
}
}}>
<Image
source={
flashMode === RNCamera.Constants.FlashMode.auto
? require('../../assets/img/flashAuto.png')
: flashMode === RNCamera.Constants.FlashMode.on
? require('../../assets/img/flashOn.png')
: require('../../assets/img/flashOff.png')
}
style={{width: 30, height: 30}}
resizeMode={'contain'}
/>
</TouchableOpacity>
{/* <TouchableOpacity
onPress={() => takePicture(camera)}
style={styles.capture}>
<Image
source={require('../../assets/img/cameraButton.png')}
style={{width: 50, height: 50}}
resizeMode={'contain'}
/>
</TouchableOpacity> */}
<TouchableOpacity
style={styles.iconContainer}
onPress={() =>
recordVideo(
camera,
recording,
seconds,
setRecording,
setSeconds,
)
}>
<EntypoIcon
style={styles.icon}
size={40}
color={recording ? 'red' : 'white'}
name="video-camera"
/>
{recording ? (
<AppText styles={styles.recordingTime}>
{secondsToMMSS(seconds)}
</AppText>
) : null}
</TouchableOpacity>
<TouchableOpacity
style={styles.capture}
onPress={(_) => {
if (type === RNCamera.Constants.Type.back) {
setType(RNCamera.Constants.Type.front);
} else {
setType(RNCamera.Constants.Type.back);
}
}}>
<Image
source={require('../../assets/img/cameraFlipIcon.png')}
style={{width: 40, height: 40}}
resizeMode={'contain'}
/>
</TouchableOpacity>
</View>
<TouchableOpacity style={styles.closeButton} onPress={() => {}}>
<IoniconsIcon
name={'ios-close'}
style={styles.closeButtonIcon}
/>
</TouchableOpacity>
</>
);
}}
</RNCamera>
</View>
);
};
export default VideoRecording;
const styles = StyleSheet.create({
container: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
backgroundColor: 'black',
},
capture: {
flex: 0,
borderRadius: 5,
padding: 15,
paddingHorizontal: 20,
alignSelf: 'center',
margin: 20,
},
cptureView: {
backgroundColor: '#ffffff',
width: 100,
height: 100,
borderRadius: 100,
alignItems: 'center',
justifyContent: 'center',
marginBottom: '20%',
marginTop: '5%',
},
camIcon: {
color: '#858181',
},
iconContainer: {
justifyContent: 'center',
alignItems: 'center',
},
icon: {
marginHorizontal: 15,
// paddingVertical: 10,
},
recordingTime: {
color: 'red',
},
closeButton: {
position: 'absolute',
backgroundColor: '#aaaaaab0',
width: 50,
height: 50,
borderRadius: 25,
justifyContent: 'center',
top: Platform.OS === 'ios' ? 45 : 10,
left: 10,
},
closeButtonIcon: {
fontSize: Platform.OS === 'ios' ? 40 : 40,
fontWeight: 'bold',
alignSelf: 'center',
lineHeight: Platform.OS === 'ios' ? 58 : 40,
},
});
Can someone help me to make it black? I tried a lot to find out way to do so that. But I could not so if someone can help me it would be grateful. Thank you very much.
Have you try this?
...
<View
style={{
flex: 0,
flexDirection: 'row',
justifyContent: 'center',
backgroundColor: "#000000", //-----------------Here?
}}>
<TouchableOpacity
style={styles.capture}
onPress={(_) => {
switch (flashMode) {
case RNCamera.Constants.FlashMode.off:
setFlashMode(RNCamera.Constants.FlashMode.auto);
...
hi i want to draw an arrow every polyline
like this image :
read this post :
How to draw an arrow on every polyline segment on Google Maps V3
this is answer my question but this post for javascript
but i use it and this is my code:
<View style={{ height: hp('50%'), width: wp('100%') }}>
<MapView
provider={PROVIDER_GOOGLE}
onLayout={this.onMapLayout}
style={styles.containerMap}
initialRegion={{
latitude: this.props.data ? this.props.data[0].YPOINT : '',
longitude: this.props.data ? this.props.data[0].XPOINT : '',
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}} >
{this.state.isMapReady && <Polyline
strokeWidth={2}
strokeColor="red"
geodesic={true}
icons={
icon = { path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW },
offset = '100%'
}
coordinates={[...this.props.data.map((value, index) => {
return { latitude: value.YPOINT, longitude: value.XPOINT }
})]}
/>
}
</MapView>
</View>
but when run i get error 'google is not defined'.
UPDATE
this is function :
import React, { Component } from 'react'
import { Text, View, StyleSheet, ScrollView, AsyncStorage, ActivityIndicator, Alert, FlatList } from 'react-native'
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
//import arrowIcon from '../../../assets/images/icon/Arrow/090.ico'
import SegmentedControlTab from "react-native-segmented-control-tab";
import { Dropdown } from 'react-native-material-dropdown';
import { getTraceOfHardware } from '../../../Store/actions';
import { connect } from 'react-redux';
import MapView, { Marker, PROVIDER_GOOGLE, Polyline } from 'react-native-maps';
import Icon from 'react-native-vector-icons/Entypo';
var moment = require('jalali-moment');
let dataDay = [{
value: 'امروز',
}, {
value: 'یک روز پیش',
}, {
value: 'دو روز پیش',
}, {
value: 'سه روز پیش',
}, {
value: 'چهار روز پیش',
}, {
value: 'پنج روز پیش',
}, {
value: 'شش روز پیش',
}, {
value: 'هفت روز پیش',
},];
const airplin = <Icon name="aircraft" size={30}/>
class mainRoutsReport extends Component {
constructor () {
super()
this.state = {
selectedIndex: 0,
selectedIndices: [0],
customStyleIndex: 0,
daySelected: '',
isMapReady: false,
tableHead: ['Head', 'Head2', 'Head3', 'Head4', 'Head5', 'Head6', 'Head7', 'Head8', 'Head9'],
widthArr: [40, 60, 80, 100, 120, 140, 160, 180, 200],
data: [],
latlon: []
// tableData: [
// ['1', '2', '3', '4', '5', '6'],
// ['1', '2', '3', '4', '5', '6']
// ]
}
}
//GET UDID
_retrieveUDID = async () => {
try {
return await AsyncStorage.getItem('#IranTracking:UDID', (error, result) => { return result })
} catch (error) {
// Error retrieving data
console.log(error)
}
};
//GET TOKEN
_retrieveToken = async () => {
try {
return await AsyncStorage.getItem('#IranTracking:Token', (error, result) => { return result })
} catch (error) {
// Error retrieving data
console.log(error)
}
};
//This method creat XML to send action.js to get List of Hardware from SOAP
async _makXML(value, index) {
udid = await this._retrieveUDID()
token = await this._retrieveToken()
var yesterday = moment().locale('fa').subtract(index + 0, 'day').format('YYYY-MM-DD')
// console.log(yesterday)
let xml = `<?xml version="1.0" encoding="utf-8"?>\
<x:Envelope xmlns:x="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tra="http://Trackinguri.org/">\
<x:Header>\
<tra:SOAPHeaderContent>\
<tra:UserName></tra:UserName>\
<tra:Password></tra:Password>\
<tra:Token>${token}</tra:Token>\
<tra:UID>${udid}</tra:UID>\
</tra:SOAPHeaderContent>\
</x:Header>\
<x:Body>\
<tra:GetTraceByHardwareID>\
<tra:HardwareID>${this.props.navigation.state.params.HID}</tra:HardwareID>\
<tra:FromDate>${yesterday} 00:00:00</tra:FromDate>\
<tra:ToDate>${yesterday} 23:59:59</tra:ToDate>\
<tra:HijriDates>true</tra:HijriDates>\
<tra:Time_Zone>Tehran</tra:Time_Zone>\
<tra:Lang>fa</tra:Lang>\
</tra:GetTraceByHardwareID>\
</x:Body>\
</x:Envelope>`;
console.log(" xml to get Tarce reports " + xml)
this.props.getTraceOfHardware(xml)
}
componentWillMount() {
this._makXML()
this.props.getTraceOfHardware()
}
componentDidMount() {
}
//this function use for day
_HandelDay(value, index) {
// var yesterday = moment().locale('fa').subtract(index,'day').format('YYYY-MM-DD')
//console.log('index of drop down is : ' + value + ' \nindex is : '+ index + '\n and date is : ' + yesterday)
//Alert.alert(yesterday)
}
handleMultipleIndexSelect = (index: number) => {
const { selectedIndices } = this.state
if (selectedIndices.includes(index)) {
this.setState(prevState => ({
...prevState,
selectedIndices: selectedIndices.filter((i) => i !== index),
}))
} else {
this.setState(prevState => ({
...prevState,
selectedIndices: [
...selectedIndices,
index,
],
}))
}
}
handleCustomIndexSelect = (index: number) => {
this.setState(prevState => ({ ...prevState, customStyleIndex: index }))
}
onMapLayout = () => {
this.setState({ isMapReady: true });
}
_renderItem = ({ item, index }) => (
// console.log(item)
<View style={{ flex: 1, height: hp('15%'), flexDirection: 'row', backgroundColor: index % 2 ? '#f3f3f3' : '#dedede', marginHorizontal: 5, alignItems: 'center' }} >
<View style={{ width: wp('15%'), alignItems: 'center', }}>
<Text style={{ marginLeft: 4, fontFamily: 'IRANSansMobile', }}>{item.TRUCKSTATE}</Text>
</View>
<View style={{ width: wp('12%'), alignItems: 'center' }}>
<Text style={{ marginLeft: 4, fontFamily: 'IRANSansMobile', }}>{item.SPEED}</Text>
</View>
<View style={{ width: wp('50%'), alignItems: 'center' }}>
<Text style={{ marginLeft: 4, fontFamily: 'IRANSansMobile', }}>{item.POSDESCRIPTION}</Text>
</View>
<View style={{ width: wp('10%'), alignItems: 'center' }}>
<Text style={{ marginLeft: 4, fontFamily: 'IRANSansMobile', }}>{item.SENTDATE}</Text>
</View>
<View style={{ width: wp('10%'), alignItems: 'center' }}>
<Text style={{ marginLeft: 4, fontFamily: 'IRANSansMobile', }}>{index + 1}</Text>
</View>
</View>
);
_renderHeadr = () => (
<View style={{ flexDirection: 'row', alignContent: 'space-between', alignItems: 'center', backgroundColor: '#5e9dcb' }}>
<View style={{ borderWidth: 0.5, width: wp('15%'), alignItems: 'center', borderTopLeftRadius: 5 }}>
<Text style={{ fontSize: 15, fontFamily: 'IRANSansMobile', }}>وضعیت</Text>
</View>
<View style={{ borderWidth: 0.5, width: wp('12%'), alignItems: 'center' }}>
<Text style={{ fontSize: 15, fontFamily: 'IRANSansMobile', }}>سرعت</Text>
</View>
<View style={{ borderWidth: 0.5, width: wp('50%'), alignItems: 'center' }}>
<Text style={{ fontSize: 15, fontFamily: 'IRANSansMobile', }}>موقعیت</Text>
</View>
<View style={{ borderWidth: 0.5, width: wp('10%'), alignItems: 'center' }}>
<Text style={{ fontSize: 15, fontFamily: 'IRANSansMobile', }}>زمان</Text>
</View>
<View style={{ borderWidth: 0.5, width: wp('10%'), alignItems: 'center', borderTopRightRadius: 5 }}>
<Text style={{ fontSize: 15, fontFamily: 'IRANSansMobile', }}>ردیف</Text>
</View>
</View>
);
render() {
const { customStyleIndex } = this.state
//console.log(this.props.navigation.state.params.HID)
//console.log(this.props.data)
return (
<View style={{ width: wp('100%'), height: hp('100%') }}>
<Dropdown animationDuration={100}
dropdownMargins={{ min: 0, max: 0 }}
dropdownOffset={{ top: 0, left: 0 }}
style={{ textAlign: 'center' }}
containerStyle={{ textAlign: 'right', backgroundColor: '#fcee97', borderWidth: 0.5, borderRadius: 13, margin: 8 }}
absoluteRTLLayout={true}
data={dataDay}
dropdownPosition={-5}
onChangeText={(value, index) => this._makXML(value, index)}
value={dataDay[0].value} />
<SegmentedControlTab
values={['نمایش متنی', 'نمایش نقشه']}
selectedIndex={customStyleIndex}
onTabPress={this.handleCustomIndexSelect}
borderRadius={0}
tabsContainerStyle={{ height: 50, backgroundColor: '#F2F2F2' }}
tabStyle={{ backgroundColor: '#ffffff', borderWidth: 0, borderColor: 'transparent' }}
activeTabStyle={{ backgroundColor: '#5e9dcb', marginTop: 2 }}
tabTextStyle={{ color: '#000000', fontWeight: 'bold', fontFamily: 'IRANSansMobile' }}
activeTabTextStyle={{ color: '#ffffff', fontFamily: 'IRANSansMobile' }}
/>
{//table
customStyleIndex === 0
&&
<View style={{ paddingBottom: wp('20%') }}>
{this.props.isLoading ? <ActivityIndicator /> : <FlatList
ListHeaderComponent={this._renderHeadr}
stickyHeaderIndices={[0]}
data={this.props.data}
renderItem={this._renderItem}//({item})=>(this._renderItem)
keyExtractor={(item, index) => index.toString()}
/>}
</View>
}
{//Map
customStyleIndex === 1
&&
<View style={{ height: hp('50%'), width: wp('100%') }}>
<MapView
provider={PROVIDER_GOOGLE}
onLayout={this.onMapLayout}
style={styles.containerMap}
initialRegion={{
latitude: this.props.data ? this.props.data[0].YPOINT : '',
longitude: this.props.data ? this.props.data[0].XPOINT : '',
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}} >
{this.state.isMapReady &&
<Polyline
strokeWidth={2}
strokeColor="red"
geodesic={true}
icons={
icon = {airplin },
offset = '100%'
}
coordinates={[...this.props.data.map((value, index) => {
return { latitude: value.YPOINT, longitude: value.XPOINT }
})]}
/>
}
</MapView>
</View>
}
</View>
)
}
}
function mapStateToProps(state) {
console.log(state)
return {
data: state.GetTraceHardware.data,
isLoading: state.GetTraceHardware.isLoading,
error: state.GetTraceHardware.error
}
}
function mapDispatchToProps(dispatch) {
return {
getTraceOfHardware: (data) => dispatch(getTraceOfHardware(data))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(mainRoutsReport);