How do I align items properly in React native - react-native

I want the narration to be Bold , and should be afar left , the amount to be on the same row as the narration , the date should be far left below the narration. But what I do does not seem to work as the transactions list is somewhat not aligned and looks like this :
tried all I could, i do not seem to see it work fine.
My code is looking thus :
import React, {useEffect, useState} from 'react';
import {
ActivityIndicator,
Button,
Image,
ImageBackground,
SafeAreaView,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
import {Header, Avatar, Icon, Card} from '#rneui/themed';
import {FlatList, ScrollView} from 'react-native-gesture-handler';
import {useNavigation} from '#react-navigation/native';
import {Tab} from '#rneui/base';
import AsyncStorage from '#react-native-async-storage/async-storage';
const HomePage = () => {
const [transaction_details, setTransaction_details] = useState([]);
const [isLoading, setLoading] = useState(true);
const navigation = useNavigation();
const Item = ({title}) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
FlatListItemSeparator = () => {
return (
<View
style={{
height: 1,
width: 350,
backgroundColor: '#D3D3D3',
}}
/>
);
};
showdata = async () => {
let token = await AsyncStorage.getItem('token');
alert(token);
};
getTransactionsList = async () => {
let token = await AsyncStorage.getItem('token');
let email = await AsyncStorage.getItem('email');
fetch('https://******************/api/fetch-transaction/' + email, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
'Authorization': `Bearer ${token}`,
},
})
.then(response => response.json())
.then(responseJson => {
setTransaction_details(responseJson.results);
setLoading(false);
});
};
useEffect(() => {
//showdata();
getTransactionsList();
});
/*useEffect(() => {
fetch('https://brotherlike-navies.000webhostapp.com/people/people.php', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
})
.then(response => response.json())
.then(responseJson => {
setTransaction_details(responseJson);
setLoading(false);
});
}, []);
*/
return (
<View style={{flex: 1}}>
<Header
containerStyle={{
backgroundColor: 'transparent',
justifyContent: 'space-around',
}}
leftComponent={
<Avatar
small
rounded
source={{
uri: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSiRne6FGeaSVKarmINpum5kCuJ-pwRiA9ZT6D4_TTnUVACpNbzwJKBMNdiicFDChdFuYA&usqp=CAU',
}}
onPress={() => console.log('Left Clicked!')}
activeOpacity={0.7}
/>
}
rightComponent={
<Icon
name={'mail-outline'}
color={'#00BB23'}
size={32}
onPress={() => navigation.navigate('Accounts')}
/>
}></Header>
<ImageBackground
source={{
uri: 'asset:/logo/bg.JPG',
}}
imageStyle={{borderRadius: 6}}
style={{
top: 15,
paddingTop: 95,
alignSelf: 'center',
width: 328,
height: 145,
borderadius: 9,
justifyContent: 'center',
alignSelf: 'center',
alignItems: 'center',
}}>
<View>
<Text style={styles.accText}>Wallet Balance</Text>
<Text style={styles.text}> 250,000 </Text>
</View>
</ImageBackground>
<View>
<Text
style={{
fontFamily: 'Poppins-Bold',
flexDirection: 'row',
paddingTop: 55,
fontSize: 15,
left: 18,
color: 'gray',
}}>
Recent Transactions
</Text>
</View>
<View style={{flex: 1, marginTop: 35}}>
{isLoading ? (
<ActivityIndicator />
) : (
<FlatList
style={{fontFamily: 'Poppins-Medium', alignSelf: 'center'}}
ItemSeparatorComponent={this.FlatListItemSeparator}
data={transaction_details}
renderItem={({item}) => {
//console.log(item);
return (
<View style={{flex: 2, flexDirection: 'row'}}>
<Text style={styles.PayeeName}>
{item.narration}
{' '}
</Text>
<Text style={styles.date_ofTransaction}>{item.date}</Text>
<Text style={styles.amountValue}>{item.amount}</Text>
</View>
);
}}
keyExtractor={item => item.id.toString()}
/>
)}
</View>
</View>
);
};
export default HomePage;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
padding: 20,
},
date_ofTransaction: {
marginTop: 20,
alignItems: 'flex-start',
alignItems: 'center',
left: -85,
fontFamily: 'Poppins-Light',
fontSize: 9,
},
paragraph: {
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
padding: 20,
},
text: {
top: -85,
fontSize: 30,
color: 'white',
textAlign: 'center',
fontFamily: 'Poppins-Bold',
},
mainContainer: {
paddingTop: 90,
justifyContent: 'center',
alignItems: 'center',
},
accText: {
top: -85,
paddingTop: 10,
justifyContent: 'center',
alignItems: 'center',
fontFamily: 'Poppins-Medium',
color: 'white',
textAlign: 'center',
},
PayeeName: {
justifyContent: 'flex-start',
alignItems: 'center',
left: 23,
fontFamily: 'Poppins-Medium',
size: 800,
fontWeight: 'bold',
},
amountValue: {
flexDirection :'row',
alignItems: 'flex-end',
fontFamily: 'Poppins-Medium',
size: 800,
fontWeight: 'bold',
},
});
The alignment is quite poor, however, I wish i could be shown a guide as how to go about this. So I could follow along etc. New to some form of Design in React native, as I am learning it on my own.

what about this approach. not sure if {' '} in you code is necessary. this aligns with space between and looks better for the ui instead of giving a random space to separate the items. and also apply the rest oft he styles to your liking, for example make font bold, etc.
<FlatList
data={transaction_details}
ItemSeparatorComponent={this.FlatListItemSeparator}
renderItem={({ item }) => {
return (
<View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
<Text>{item.narration}</Text>
<Text>{item.amount}</Text>
</View>
<Text>{item.date}</Text>
</View>
)
}}
keyExtractor={(item) => item.id.toString()}
/>

Related

Styling problems How do I style this?

I have this as a worry
this is what the app home page looks like
some things are not aligned the way i want it to be, and its not nice. I am trying to get the date beneath the narration with a much smaller text and move the avatar somewhat beneath the recent transactions.
How do i align it properly
My source code is looking thus
import React, {useEffect, useState} from 'react';
import {
ActivityIndicator,
Button,
Image,
ImageBackground,
SafeAreaView,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
import {Header, Avatar, Icon, Card} from '#rneui/themed';
import {FlatList, ScrollView} from 'react-native-gesture-handler';
import {useNavigation} from '#react-navigation/native';
import {Tab} from '#rneui/base';
import AsyncStorage from '#react-native-async-storage/async-storage';
import TextAvatar from 'react-native-text-avatar';
const HomePage = () => {
const [transaction_details, setTransaction_details] = useState([]);
const [isLoading, setLoading] = useState(true);
const navigation = useNavigation();
const Item = ({title}) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
FlatListItemSeparator = () => {
return (
<View
style={{
height: 1,
left: 21,
width: 350,
backgroundColor: '#D3D3D3',
}}
/>
);
};
showdata = async () => {
let token = await AsyncStorage.getItem('token');
alert(token);
};
getTransactionsList = async () => {
let token = await AsyncStorage.getItem('token');
let email = await AsyncStorage.getItem('email');
fetch(
'https://webserver-migospay.onrender.com/api/user-data/get-transactionby-email/' +
email,
{
method: 'GET',
headers: {
'Content-type': 'application/json',
Authorization: `Bearer ${token}`,
},
},
)
.then(response => response.json())
.then(responseJson => {
setTransaction_details(responseJson);
setLoading(false);
});
};
useEffect(() => {
//showdata();
getTransactionsList();
});
/*useEffect(() => {
fetch('https://brotherlike-navies.000webhostapp.com/people/people.php', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
})
.then(response => response.json())
.then(responseJson => {
setTransaction_details(responseJson);
setLoading(false);
});
}, []);
*/
return (
<View style={{flex: 1}}>
<Header
containerStyle={{
backgroundColor: 'transparent',
justifyContent: 'space-around',
}}
leftComponent={
<Avatar
small
rounded
source={{
uri: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSiRne6FGeaSVKarmINpum5kCuJ-pwRiA9ZT6D4_TTnUVACpNbzwJKBMNdiicFDChdFuYA&usqp=CAU',
}}
onPress={() => console.log('Left Clicked!')}
activeOpacity={0.7}
/>
}
rightComponent={
<Icon
name={'mail-outline'}
color={'#00BB23'}
size={32}
onPress={() => navigation.navigate('Accounts')}
/>
}></Header>
<ImageBackground
source={{
uri: 'asset:/logo/bg.JPG',
}}
imageStyle={{borderRadius: 6}}
style={{
top: 15,
paddingTop: 95,
alignSelf: 'center',
width: 328,
height: 145,
borderadius: 9,
justifyContent: 'center',
alignSelf: 'center',
alignItems: 'center',
}}>
<View>
<Text style={styles.accText}>Wallet Balance</Text>
<Text style={styles.text}> 250,000 </Text>
</View>
</ImageBackground>
<View>
<Text
style={{
fontFamily: 'Poppins-Bold',
flexDirection: 'row',
paddingTop: 35,
fontSize: 15,
left: 30,
color: 'gray',
}}>
Recent Transactions
</Text>
</View>
<View style={{flex: 1, marginTop: 35}}>
{isLoading ? (
<ActivityIndicator />
) : (
<FlatList
data={transaction_details}
ItemSeparatorComponent={FlatListItemSeparator}
renderItem={({item}) => {
return (
<View>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
}}>
<TextAvatar
backgroundColor={'#00BB23'}
textColor={'#f2f2f2'}
size={60}
type={'circle'}
// optional
>
{item.narration}
</TextAvatar>
<Text style={styles.narration}>{item.narration}</Text>
<Text style={styles.amountText}>{item.amount}</Text>
</View>
<Text style={styles.date_transaction}>{item.created_at}</Text>
</View>
);
}}
keyExtractor={item => item._id.toString()}
/>
)}
</View>
</View>
);
};
export default HomePage;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
padding: 20,
},
paragraph: {
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
padding: 20,
},
text: {
top: -85,
fontSize: 30,
color: 'white',
textAlign: 'center',
fontFamily: 'Poppins-Bold',
},
mainContainer: {
paddingTop: 90,
justifyContent: 'center',
alignItems: 'center',
},
accText: {
top: -85,
paddingTop: 10,
justifyContent: 'center',
alignItems: 'center',
fontFamily: 'Poppins-Medium',
color: 'white',
textAlign: 'center',
},
PayeeName: {
justifyContent: 'flex-start',
flexWrap: 'wrap',
fontFamily: 'Poppins-Medium',
size: 800,
fontWeight: 'bold',
},
amountValue: {
textAlign: 'right',
fontFamily: 'Poppins-Medium',
size: 800,
fontWeight: 'bold',
},
narration: {
fontFamily: 'Poppins-ExtraBold',
size: 700,
left: -65,
},
date_transaction: {
fontFamily: 'Poppins-Regular',
size: 10,
left: 21,
},
amountText: {
fontFamily: 'Poppins-ExtraBold',
size: 1000,
right: 32,
},
});
Please I need help as I am not very good at styling here. Just need more guidiance in this case.
You need to wrap the item.narration and the item.created_at inside a <View> and have them aligned vertically. Basically wrap them on a View and swap item.amonut for item.created_at and style the <View> with a flex: 1. Then change the font size for the date.
<FlatList
data={transaction_details}
ItemSeparatorComponent={FlatListItemSeparator}
renderItem={({item}) => {
return (
<View>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
}}>
<TextAvatar
backgroundColor={'#00BB23'}
textColor={'#f2f2f2'}
size={60}
type={'circle'}
// optional
>
{item.narration}
</TextAvatar>
<View style={{ flex: 1 }}> // Add styling as needed
<Text style={styles.narration}>{item.narration} </Text>
<Text style={styles.date_transaction}> {item.created_at}</Text> // Change the font size as you like
</View>
<Text style={styles.amountText}>{item.amount}</Text>
</View>
<Text style={styles.amountText}>{item.amount}</Text>
</View>
);
}}
keyExtractor={item => item._id.toString()}
/>

Data wont Display correctly on Flat list in React native

So far i have got 2 problems,
1.) I need to have this pulled from a REST api (Which it does and shows the names on the system) but it gives this very funny warning "each child in a list should have a unique key prop" looking thru i know its an issue and somehow i need to solve it
this is what the Error looks like
secondly i want the Flatlist to display like this
Other than that, i get something like this
My code is looking like this
import React, {useEffect, useState} from 'react';
import {
Image,
ImageBackground,
SafeAreaView,
StyleSheet,
Text,
View,
} from 'react-native';
import {Header, Avatar, Icon, Card} from '#rneui/themed';
import {FlatList, ScrollView} from 'react-native-gesture-handler';
const HomePage = () => {
const [transaction_details, setTransaction_details] = useState([]);
const Item = ({title}) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
const ItemData = ({item}) => <Item title={item.name} />;
useEffect(() => {
fetch('https://brotherlike-navies.000webhostapp.com/people/people.php', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
})
.then(response => response.json())
.then(responseJson => {
setTransaction_details(responseJson);
});
}, []);
return (
<View>
<Header
containerStyle={{
backgroundColor: 'transparent',
justifyContent: 'space-around',
}}
leftComponent={
<Avatar
small
rounded
source={{
uri: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSiRne6FGeaSVKarmINpum5kCuJ-pwRiA9ZT6D4_TTnUVACpNbzwJKBMNdiicFDChdFuYA&usqp=CAU',
}}
onPress={() => console.log('Left Clicked!')}
activeOpacity={0.7}
/>
}
rightComponent={
<Icon
name={'add-circle-outline'}
color={'#00BB23'}
size={32}
onPress={() => console.log('Right Clicked!')}
/>
}></Header>
<View
style={{
flex: 1,
justifyContent: 'center',
borderadius: 9,
alignItems: 'center',
}}>
<ImageBackground
source={{
uri: 'asset:/logo/bg.JPG',
}}
imageStyle={{borderRadius: 6}}
style={{
flex: 1,
width: 350,
height: 150,
borderadius: 9,
justifyContent: 'center',
alignItems: 'center',
marginTop: 15,
}}>
<View
style={{
position: 'absolute',
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={styles.accText}>Wallet Balance</Text>
<Text style={styles.text}> 250,000 </Text>
</View>
</ImageBackground>
</View>
<View>
<Text
style={{
fontFamily: 'Poppins-Bold',
flexDirection: 'column',
fontSize: 14,
margin: 10,
top: 170,
left: 18,
color: 'gray',
}}>
Recent Transactions
</Text>
</View>
<View>
<FlatList
data={transaction_details}
renderItem={ItemData}
keyExtractor={(item, index) =>item.id}
/>
</View>
</View>
);
};
export default HomePage;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
padding: 20,
},
paragraph: {
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
padding: 20,
},
text: {
top: 50,
fontSize: 30,
color: 'white',
textAlign: 'center',
fontFamily: 'Poppins-Bold',
},
mainContainer: {
flex: 1,
paddingTop: 90,
justifyContent: 'center',
alignItems: 'center',
},
accText: {
top: 50,
paddingTop: 10,
justifyContent: 'center',
alignItems: 'center',
fontFamily: 'Poppins-Medium',
color: 'white',
textAlign: 'center',
},
});
Now i am a bit worried, where can I start from. I need some guidance with this, kind of new with something like this.

Unable to Scroll using Flatlist in React native

So i have tried couple of things, data pulled from the REST api works fine without trouble, but when i put it to Flatlist, it does not scroll. Tried countless things I saw on the internet, and still , it does not seem to work.
Below is a snippet i used, to display data from the REST api to the application :
<View>
{isLoading ? <ActivityIndicator/> : <FlatList
style={{fontFamily: 'Poppins-Medium', top: 170, left: 23}}
ItemSeparatorComponent={this.FlatListItemSeparator}
data={transaction_details}
renderItem={({item}) => (
<View style={{paddingTop: 20,flexDirection: 'row', height: 75}}>
<Image source={{uri: item.avatar}} style={{width:50, height:50, borderRadius:25,overflow:'hidden'}}/>
<Text style={styles.PayeeName}>{item.name}{" "}</Text>
<Text style={styles.date_ofTransaction}>{item.date}</Text>
<Text style={styles.amountValue}>{item.amount}</Text>
</View>
)}
keyExtractor={(item) => item.id .toString()}
scrollEnabled={true}
/>}
</View>
Looking over, i saw something like View style={{flex:1}} should I have to try this, the whole thing disappears speedily. I dont know what else I have to try hence, this.
I need help with this.
Thank you!
New Edits
done the edit you asked me to, now there are still some spaces there. Do not know how they came about,
I looks like this now so far
Here is the new Source code
import React, {useEffect, useState} from 'react';
import {
ActivityIndicator,
Image,
ImageBackground,
SafeAreaView,
StyleSheet,
Text,
View,
} from 'react-native';
import {Header, Avatar, Icon, Card} from '#rneui/themed';
import {FlatList, ScrollView} from 'react-native-gesture-handler';
import {Tab} from '#rneui/base';
const HomePage = () => {
const [transaction_details, setTransaction_details] = useState([]);
const[isLoading,setLoading] = useState(true);
const Item = ({title}) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
FlatListItemSeparator = () => {
return (
<View
style={{
height: 1,
width: 350,
backgroundColor: '#D3D3D3',
}}
/>
);
};
useEffect(() => {
fetch('https://brotherlike-navies.000webhostapp.com/people/people.php', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
})
.then(response => response.json())
.then(responseJson => {
setTransaction_details(responseJson);
setLoading(false);
});
}, []);
return (
<View style={{flex:1, borderWidth:1}}>
<Header
containerStyle={{
backgroundColor: 'transparent',
justifyContent: 'space-around',
}}
leftComponent={
<Avatar
small
rounded
source={{
uri: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSiRne6FGeaSVKarmINpum5kCuJ-pwRiA9ZT6D4_TTnUVACpNbzwJKBMNdiicFDChdFuYA&usqp=CAU',
}}
onPress={() => console.log('Left Clicked!')}
activeOpacity={0.7}
/>
}
rightComponent={
<Icon
name={'add-circle-outline'}
color={'#00BB23'}
size={32}
onPress={() => console.log('Right Clicked!')}
/>
}></Header>
<View
style={{
flex: 1,
justifyContent: 'center',
borderadius: 9,
alignItems: 'center',
borderWidth:1
}}>
<ImageBackground
source={{
uri: 'asset:/logo/bg.JPG',
}}
imageStyle={{borderRadius: 6}}
style={{
width: 350,
height: 150,
borderadius: 9,
justifyContent: 'center',
alignItems: 'center',
}}>
<View>
<Text style={styles.accText}>Wallet Balance</Text>
<Text style={styles.text}> 250,000 </Text>
</View>
</ImageBackground>
</View>
<View style={{borderWidth:1}}>
<Text
style={{
fontFamily: 'Poppins-Bold',
flexDirection: 'row',
fontSize: 15,
left: 18,
color: 'gray',
}}>
Recent Transactions
</Text>
</View>
<View style={{flex:1, borderWidth:1}}>
{isLoading ? <ActivityIndicator/> : <FlatList
style={{fontFamily: 'Poppins-Medium', left: 23}}
ItemSeparatorComponent={this.FlatListItemSeparator}
data={transaction_details}
renderItem={({item}) => (
<View style={{flex:1,flexDirection: 'row'}}>
<Image source={{uri: item.avatar}} style={{width:50, height:50, borderRadius:25,overflow:'hidden'}}/>
<Text style={styles.PayeeName}>{item.name}{" "}</Text>
<Text style={styles.date_ofTransaction}>{item.date}</Text>
<Text style={styles.amountValue}>{item.amount}</Text>
</View>
)}
keyExtractor={(item) => item.id .toString()}
/>}
</View>
</View>
);
};
export default HomePage;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
padding: 20,
},
date_ofTransaction: {
marginTop: 20,
alignItems:'flex-start',
alignItems:'center',
left: -75,
fontFamily: 'Poppins-Light',
size: 4,
},
paragraph: {
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
padding: 20,
},
text: {
top: -85,
fontSize: 30,
color: 'white',
textAlign: 'center',
fontFamily: 'Poppins-Bold',
},
mainContainer: {
paddingTop: 90,
justifyContent: 'center',
alignItems: 'center',
},
accText: {
top: -85,
paddingTop: 10,
justifyContent: 'center',
alignItems: 'center',
fontFamily: 'Poppins-Medium',
color: 'white',
textAlign: 'center',
},
PayeeName: {
justifyContent: 'flex-start',
alignItems:'center',
left: 23,
fontFamily: 'Poppins-Medium',
size: 800,
fontWeight:'bold'
},
amountValue: {
alignItems: 'flex-end',
alignItems:'center',
right: -25,
fontFamily: 'Poppins-Medium',
size: 800,
fontWeight:'bold'
}
});
Method 1
It does not scroll because your view is restricting it. Try replacing view with <></> (Fragments).
Method 2
The other way of solving this is adding flex 1 in view container, it disappears because its parent also needs to be set to flex. So find all parents that have view in it and add flex 1 in them Then it will work

how to validate DateTimePickerModal with yup and formik in React native?

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

Flatlist not re-rendering after deleting an item from the state

I'm working on a react native application,
In this application I have an image capturing the view, If the user captures an image it will be stored in the state hook, if something stored it will be displayed in Flatlist.
If we think the user needs to remove an item from the list, that I have provided a delete button. When a user clicks on it the item should be removed from the state and update the Flatlist.
My question is: after removing an item from the state my view is not re-render. I can guarantee that data is successfully removed from the state, but my Flatlist not updating.
My code as follows, please help me to find an answer. Thanks in advance.
below code used to remove the item from the state.
const [selectedFiles, setSelectedFiles] = useState([]);
const removeItemFromArray = (index: number) => {
let imagesArray = selectedFiles;
imagesArray.splice(index, 1);
setSelectedFiles(imagesArray);
}
flatlist
<FlatList
showsHorizontalScrollIndicator={false}
data={selectedFiles}
renderItem={({ item, index }) => {
return (
<ImagePreviewSlider
itemData={item}
viewImage={() => viewImage(index)}
deleteItem={() => removeItemFromArray(index)}
/>
);
}}
/>
---------- complete code --------------
photoUpload.tsx
import React, { useState } from "react";
import {
View,
Text,
StyleSheet,
ScrollView,
Image,
ImageBackground,
TouchableOpacity,
Modal,
FlatList
} from "react-native";
import ImagePicker from 'react-native-image-picker/lib/commonjs';
import ComponentStyles, { FONT_FAMILY, COLORS } from "../../../../constants/Component.styles";
import IconF from 'react-native-vector-icons/FontAwesome';
import ActionButton from "../../../../components/ActionButton";
import ImagePreviewSlider from "../../../../subComponents/ProgressBarWithImage";
import InspectionCheckListItem from './InspectionCheckListRow';
const ImageUpload = props => {
/**
* image capturing and upload tab view
*/
const [modalVisible, setModalVisible] = useState(false);
const [selectedFiles, setSelectedFiles] = useState([]);
/**
* used to open popup dialog / state hook will be updated.
*/
const openModal = () => {
// setModalVisible(true);
props.navigation.navigate('Inspection result');
}
/**
* when user click on previous button this method will be worked.
*/
const previousTab = () => {
props.navigation.navigate('Inspection checkList');
}
/**
* below method used to close the popup dialog.
*/
const colseModal = () => {
setModalVisible(false);
}
/**
* #chooseFile method is a alert dialog / here user can select camera or galery
* #ImagePicker method used to open camera and collect picture / select picture from galery(function)
*/
const chooseFile = () => {
const options = {
title: 'Select an option',
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.showImagePicker(options, (response) => {
// console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
// let source = response;
// You can also display the image using data:
let source = {
uri: 'data:image/jpeg;base64,' + response.data
};
setImagesToHooks(source);
}
});
};
/**
*
* #param newImage base64- converted image
*/
const setImagesToHooks = (newImage) => {
// This will update the array. Refer the blog link for more information.
let imagesArray = [...selectedFiles, newImage];
setSelectedFiles(imagesArray);
};
const removeItemFromArray = (index: number) => {
let imagesArray = selectedFiles;
imagesArray.splice(index, 1);
setSelectedFiles(imagesArray);
}
const viewImage = (index: number) => {
console.log("view item : ######## : ");
}
return (
<View style={{ backgroundColor: COLORS.WHITE_BG, flex: 1, borderTopLeftRadius: 30, borderTopRightRadius: 30 }}>
<View style={{ flexDirection: 'row', width: '100%', height: '90%' }}>
<View style={{ width: '50%', height: '100%', padding: "2%" }}>
<TouchableOpacity style={{ width: '100%', height: 300, alignItems: 'center', justifyContent: 'center' }} onPress={chooseFile}>
<ImageBackground style={{ width: '100%', height: 300, alignItems: 'center', justifyContent: 'center' }} resizeMode={'stretch'}
source={require('../../../../assets/images/Rectangle_image_upload.png')} >
<IconF style={{ color: COLORS.ASH_AE }} name="camera" size={80} />
<Text style={{ color: COLORS.ASH_AE }}>Take image or upload from device</Text>
</ImageBackground>
</TouchableOpacity>
</View>
<View style={{ width: '50%', marginTop: 5, }}>
{/* <ProgressBar array={selectedFiles} deleteItem={(value) => deleteItemFromArray(value)}/> */}
<FlatList
showsHorizontalScrollIndicator={false}
data={selectedFiles}
renderItem={({ item, index }) => {
return (
<ImagePreviewSlider
itemData={item}
viewImage={() => viewImage(index)}
deleteItem={() => removeItemFromArray(index)}
/>
);
}}
/>
</View>
</View>
<View style={styles.actionButton}>
<ActionButton
title={'Previous'}
color={COLORS.PINK}
customBtnStyle={{
height: 65,
width: '85%',
}}
onPress={() => previousTab()}
/>
<ActionButton
title={'Next'}
color={COLORS.GREEN_42}
customBtnStyle={{
height: 65,
width: '100%',
}}
onPress={() => openModal()}
/>
</View>
<View>
<Modal
animationType="fade"
transparent={true}
visible={modalVisible} >
<View style={styles.modalContainer}>
<View style={styles.centeredView}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<TouchableOpacity style={{ flex: 0.2 }} onPress={colseModal}>
<Image source={require('../../../../assets/images/ic-close.png')} style={{ height: 20, width: 20, marginRight: 10 }} />
</TouchableOpacity>
</View>
<View style={styles.columnView}>
<Text style={styles.contentTitle}>Inspection of pharmacies</Text>
<Text style={styles.contentSubTitle}>Checklist:</Text>
<View style={styles.rowView}>
<View style={{ flex: 1, alignSelf: 'center' }} >
<Text style={styles.tableText}>Description</Text>
</View>
<View style={{ flex: 1, alignSelf: 'center' }} >
<Text style={styles.tableText}>Validiry</Text>
</View>
<View style={{ flex: 1, alignSelf: 'center' }} >
<Text style={styles.tableText}>Remark</Text>
</View>
</View>
</View>
<View style={{ flex: 2, width: '100%', flexDirection: 'column' }}>
{/* <InspectionCheckListItem array={InspectionList.items} /> */}
</View>
</View>
</View>
</Modal>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
modalContainer: {
position: 'absolute',
width: '100%',
height: '100%',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(100,100,100, 0.5)',
padding: 20,
},
centeredView: {
position: 'relative',
width: '90%',
height: '90%',
backgroundColor: COLORS.WHITE_FC,
padding: 20,
},
inspectionNumber: {
flex: 1.5,
fontSize: 18,
color: COLORS.BLUE_69,
fontFamily: FONT_FAMILY.BOLD
},
modalTitle: {
flex: 2,
fontSize: 12,
color: COLORS.GREEN_42,
fontFamily: FONT_FAMILY.BOLD
},
contentTitle: {
fontSize: 18,
color: COLORS.BLUE_69,
fontFamily: FONT_FAMILY.REGULAR,
},
contentSubTitle: {
fontSize: 18,
color: COLORS.BLUE_69,
fontFamily: FONT_FAMILY.BOLD,
},
columnView: {
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center'
},
rowView: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginTop: '5%'
},
tableText: {
fontSize: 18,
color: COLORS.BLUE_69,
fontFamily: FONT_FAMILY.LIGHT,
justifyContent: 'center',
alignSelf: 'center'
},
actionButton: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'flex-end',
position: 'relative',
bottom: '2%',
left: 0,
}
});
export default ImageUpload;
ProgressBarWithImage.tsx
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
TouchableOpacity
} from "react-native";
import IconMC from 'react-native-vector-icons/MaterialCommunityIcons';
import { ProgressBar } from '#react-native-community/progress-bar-android';
import { COLORS, FONT_FAMILY } from "../constants/Component.styles";
const ProgressBarWithImage = props => {
return (
<View style={styles.container}>
<View style={{ justifyContent: 'center', alignItems: 'center', backgroundColor: COLORS.PINK, opacity: 0.3, height: 40, width: 40, borderRadius: 100 }}>
<TouchableOpacity onPress={props.viewImage}>
<IconMC style={{ color: COLORS.PINK, opacity: 100 }} name="file-image" size={30} />
</TouchableOpacity>
</View>
<View style={{ marginLeft: 20, }}>
<View style={{ flexDirection: 'row', alignItems: 'center', width: '100%' }}>
<Text style={{ fontSize: 15, color: COLORS.BLUE_2C, fontFamily: FONT_FAMILY.SEMI_BOLD }}>Photo01.PNG</Text>
<View style={{ flex: 1 }} />
<TouchableOpacity onPress={props.deleteItem}>
<IconMC style={{ color: COLORS.ASH_AE, opacity: 100, marginLeft: 60, }} name="close" size={20} />
</TouchableOpacity>
</View>
<Text style={{ fontSize: 15, color: COLORS.ASH_AE, fontFamily: FONT_FAMILY.SEMI_BOLD }}>7.5Mb</Text>
<ProgressBar
styleAttr="Horizontal"
indeterminate={false}
progress={1}
/>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'row',
width: '100%',
marginTop: 20,
},
});
export default ProgressBarWithImage;
Just use extraData prop of flatList to re-render flatList.
Simply add this state
const [refreshFlatlist, setRefreshFlatList] = useState(false);
And on in removeItemFromArray function add the following line
setRefreshFlatList(!refreshFlatlist)
finally, in flatList add this prop
extraData(refreshFlatlist)