I am bit new to react native, I am fetching parameters from my previous screen and based on that parameters i’m getting data from API.
I’m using flatlist to display those data (in touchableOpacity), now I want that if any item clicked – its border color should get changed from RED to GREEN.
below is my code
import { View, Text,TextInput, TouchableOpacity, SafeAreaView, FlatList } from 'react-native'
import React, { useEffect, useState } from 'react'
import { useNavigation, useRouter, useLocalSearchParams } from 'expo-router'
import { StyleSheet } from 'react-native';
import {Colors} from '../../../constants/Colors'
export default function index() {
const navigation = useNavigation();
const router = useRouter();
const { course, div } = useLocalSearchParams()
console.log({course, div})
const [data, setData] = useState(null);
const [selectedStuId, setSelectedStuId] = React.useState(1);
const changeSelectedStudent = function (id) {
console.log(selectedStuId);
setSelectedStuId(id);
console.log(selectedStuId);
};
useEffect(()=>{
navigation.setOptions({
headerShown:false
})
},[])
useEffect(()=>{
const getUserAuthentication = async () => {
try {
if(!course && !div)
{
ToastAndroid.show('Something went wrong',ToastAndroid.BOTTOM);
return;
}
const response = await fetch(
'https://www.mywebsite.com/fetchStudentListAPI.php',
{
method:'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: course,
secondParam: div
}),
}
);
const json = await response.json();
setData(json);
// return json;
console.log(json[0].stu_name);
} catch (error) {
console.error(error);
}
};
getUserAuthentication();
},[])
return (
<View style={{
padding:25,
paddingTop:50,
backgroundColor:Colors.WHITE,
height:'100%'
}}>
<Text style={{
fontFamily:'Poppins-Bold',
fontSize:30,
textAlign:'center'
}}>Take Attendance</Text>
<Text style={{
fontFamily:'Poppins-Bold',
fontSize:18,
textAlign:'center'
}}>Course: {course} Div: {div}</Text>
<SafeAreaView style={styles.container}>
<FlatList
data={data}
extraData={setSelectedStuId}
renderItem={({ item }) =>
<TouchableOpacity
onPress={() => {
changeSelectedStudent(item.stu_id);
}}>
<Text style={item.stu_id === setSelectedStuId // <-- match id property
? styles.item
: styles.itemSelected}>{item.stu_roll_no} {item.stu_name}</Text>
</TouchableOpacity>
}
keyExtractor={(item) => item.stu_id}
/>
</SafeAreaView>
<TouchableOpacity style={{
padding:20,
backgroundColor:Colors.PRIMARY,
borderRadius:15,
marginTop:50
}}>
<Text style={{
color:Colors.WHITE,
textAlign:'center',
fontFamily:'Poppins'
}}> Submit </Text>
</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({
container: {
padding: 50,
flex: 1,
},
item: {
padding: 20,
fontSize: 15,
marginTop: 5,
borderWidth:1,
borderRadius:15,
borderColor:Colors.GREEN,
fontFamily:'Poppins',
},
itemSelected: {
padding: 20,
fontSize: 15,
marginTop: 5,
borderWidth:1,
borderRadius:15,
borderColor:Colors.RED,
fontFamily:'Poppins',
},
});