Reputation: 51
This program is supposed to change the background color of each individual item from this list when it is clicked. For example, when one item is pressed it will turn from pink to blue. My main issue is figuring out how to make/ connect a function with the item so that it will change its background color.
import React, { useState } from 'react'; import { StyleSheet, Text, View, FlatList, TouchableOpacity } from 'react-native';
export default function App() {
const [people, setPeople] = useState([
{ name: 'Day 1', id: '1' },
{ name: 'Day 2', id: '2' },
{ name: 'Day 3', id: '3' },
]);
const pressHandler = (id) => {
setPeople((prevPeople) => {
return prevPeople.{/*changeColorfunction*/};
});
};
return (
<View style={styles.container}>
<Text>Task 1</Text>
<FlatList
numColumns={5}
keyExtractor={(item) => item.id}
data={people}
renderItem={({ item }) => (
<TouchableOpacity onPress={() => pressHandler(item.id)}>
<Text style={styles.item}>{item.name}</Text>
</TouchableOpacity>
)}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 40,
paddingHorizontal: 20,
backgroundColor: '#fff',
},
item: {
flex: 1,
marginHorizontal: 10,
marginTop: 24,
padding: 7,
backgroundColor: 'pink',
fontSize: 14,
},
});
Upvotes: 0
Views: 1155
Reputation: 4741
I would suggest you wrap the item into its own component and handle the logic internally for each item.
// ListItem.js
export default function ListItem(props) {
const { name } = props;
const [pressed, setPressed] = useState(false);
const onPress = () => {
setPressed(prevPressed => !prevPressed);
}
return (
<TouchableOpacity onPress={onPress}>
<View style={{ backgroundColor : pressed ? 'red' : 'blue' }}>
<Text style={styles.item}>{props.name}</Text>
</View>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
item: {
flex: 1,
marginHorizontal: 10,
marginTop: 24,
padding: 7,
fontSize: 14,
}
});
// App.js
export default function App() {
const [people, setPeople] = useState([
{ name: 'Day 1', id: '1' },
{ name: 'Day 2', id: '2' },
{ name: 'Day 3', id: '3' }
]);
return (
<View style={styles.container}>
<Text>Task 1</Text>
<FlatList
numColumns={5}
keyExtractor={(item) => item.id}
data={people}
renderItem={({ item }) => (
<ListItem name={item.name} />
)}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 40,
paddingHorizontal: 20,
backgroundColor: '#fff',
}
});
Upvotes: 1