Having trouble creating a toggle button that changes icon and color when clicked? I'm following a tutorial but encountered an issue.
Despite attempting different modifications, the same error persists: "Cannot Find Variable: setState"
The snippet of code causing the problem:
import { View, Text, StyleSheet ,Image, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { Caption } from "react-native-paper"
const FlagSection = (props) => {
const state = {
heartIcon: "ios-heart-outline",
liked: false
}
const toggleLike = () => {
setState({
liked: !state.liked
})
if(state.heartIcon){
setState({
heartIcon: "ios-heart"
})
}else{
setState({
heartIcon: "ios-heart-outline"
})
}
}
return (
<View style={ styles.container }>
<View style={ {flex:1} }>
<View style= {styles.flagInfo}>
<View style= {styles.imageContent}>
<Image
source={ props.detail.flag }
size={60}
/>
<View style= {styles.currencyContent}>
<Text> {props.detail.abbreviation} </Text>
<Caption style={ styles.caption }> {props.detail.name} </Caption>
</View>
<View style= {styles.likeButton}>
<TouchableOpacity onPress={ toggleLike }>
<Icon name={state.heartIcon} size={40} style={{color: state.heartIcon === "ios-heart-outline" ? "black" : "red"}}/>
</TouchableOpacity>
</View>
</View>
</View>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
flagInfo: {
paddingLeft: 20,
borderWidth: 5,
},
imageContent: {
flexDirection: "row",
marginTop: "3%",
},
currencyContent: {
marginLeft: "3%",
flexDirection: "column"
},
caption: {
fontSize: 16,
paddingTop: "3%",
lineHeight: 14,
},
likeButton: {
flexDirection: "row",
justifyContent: "flex-end",
marginLeft: "auto"
}
});
export default FlagSection;