React Native: change component colour using TouchableOpacity onPress() - react-native

I'm making a to-do list to display on a page where the user can click on an icon to mark the task as done, in which the background colour of the corresponding task changes. The issue I'm having is I reuse the 'task' component and cannot specify which component's background should change colour. Hence, clicking any of the icons changes only one component's background colour. GIF of what I mean is below:
Only one component is changing
My code is as follows:
export default function GoalItems(props) {
const goals = props.goals;
if (goals == 1) {
return <Goal goal="Goal 1" />;
} else if (goals == 2) {
return (
<View>
<Goal goal="Goal 1" />
<View style={{marginVertical: 15}} />
<Goal goal="Goal 2" />
</View>
);
} else {
return (
<View>
<Goal goal="Goal 1" />
<View style={{marginVertical: 15}} />
<Goal goal="Goal 2" />
<View style={{marginVertical: 15}} />
<Goal goal="Goal 3" />
</View>
);
}
}
function Goal(props) {
const text = props.goal;
const [checkBox, setCheckBox] = useState(false);
const [checkBoxValue, setCheckBoxValue] = useState(
'ios-checkmark-circle-outline',
);
const [iconColour, setIconColour] = useState('#FF1744');
const [goalColour, setGoalColour] = useState('#64B5F6');
onPressCheckBox = () => {
setCheckBox(!checkBox);
if (checkBox) {
setCheckBoxValue('ios-checkmark-circle');
setIconColour('#1ABC9C');
setGoalColour('#1ABC9C');
} else {
setCheckBoxValue('ios-checkmark-circle-outline');
setIconColour('#FF1744');
setGoalColour('#64B5F6');
}
};
return (
<View style={styles.goalContainer}>
<View style={[{backgroundColor: goalColour}, styles.goal]}>
<Text style={styles.text}>{text}</Text>
</View>
<TouchableOpacity onPress={() => this.onPressCheckBox()}>
<Icon
name={checkBoxValue}
size={40}
style={styles.checkbox}
color={iconColour}
/>
</TouchableOpacity>
</View>
);
}
And the I just render <GoalItems goals={num_of_goals} /> in my main app page. I know its poorly coded with the if statements but I'm not sure how to return X amount of <GoalItems /> given num_of_goals, but that's a separate issue...
Any advice would be appreciated. Thanks in advance!

i think the reason is asynchronous.
When you call setCheckBox(!checkBox) you must wait to it working. When it done, you continue handle new state.
onPressCheckBox = () => {
setCheckBox(!checkBox)
};
useEffect(() => {
if (checkBox) {
setCheckBoxValue('ios-checkmark-circle');
setIconColour('#1ABC9C');
setGoalColour('#1ABC9C');
} else {
setCheckBoxValue('ios-checkmark-circle-outline');
setIconColour('#FF1744');
setGoalColour('#64B5F6');
}
}, [])

Related

How to use hooks as image's source in react native?

Im making this menu that when the user clicks at an option, it changes the background image, but i cant use the hook that i created as a parameter to the source of the image. Can someone find where im wrong and how to fix it?
Heres the part of my code referents to the menu and the hooks:
export function Home(){
let imagens = {
vovo: '../assets/vovoJuju.png',
mc: '../assets/mcJuju.png',
pato: '../assets/patoJuju.png',
}
const navigation = useNavigation<any>();
const [showBottomSheet, setShowBottomSheet] = React.useState(false);
const [param, setParam] = useState(1);
const [skin, setSkin] = useState('vovo')
const hide = () => {
setShowBottomSheet(false)
}
function handleAbout(){
navigation.navigate('About');
}
useEffect(() => {
if(param==1){
setSkin('vovo');
}
else if(param==2){
setSkin('mc');
}
else if(param==3){
setSkin('pato');
}
})
return(
<SafeAreaView style={styles.container}>
<TouchableOpacity onPress={handleAbout}>
<Counter />
</TouchableOpacity>
<TouchableOpacity onPress={() => {
setShowBottomSheet(true)
}}
>
<Image source={skin} style={styles.imgvj}/>
</TouchableOpacity>
<BottomSheet show={showBottomSheet} height={290} onOuterClick={hide}>
<Pressable onPress={hide} style={styles.bottomSheetContent}>
<Image source={barrinhaLoja} style={styles.barra}/>
</Pressable>
<View style={styles.conteudoLoja}>
<View style={styles.marginLeft48}>
<TouchableOpacity onPress={() => {
setParam(1);
}}>
<Image source={vovoJuju} style={styles.vovo}/>
<Text style={styles.legendasLoja}>Vovó Juju</Text>
</TouchableOpacity>
</View>
<View>
<TouchableOpacity onPress={() => {
setParam(2);
}}>
<Image source={mcJuju} style={styles.mc}/>
<Text style={styles.legendasLoja}>MC Juju</Text>
</TouchableOpacity>
</View>
<View>
<TouchableOpacity onPress={() => {
setParam(3);
}}>
<Image source={patoJuju} style={styles.pato}/>
<Text style={styles.legendasLoja}>Pato Juju</Text>
</TouchableOpacity>
</View>
</View>
</BottomSheet>
I created the "let imagens", "const param", "const skin" and the "useEffect trying" to make this function. I already tried using the source in different ways such as source={skin} and source={imagens[skin]} but it havent worked.
I'm not certain if this solves your problem, but here's how the first few lines of your component should look like without useEffect:
const imagens = {
vovo: '../assets/vovoJuju.png',
mc: '../assets/mcJuju.png',
pato: '../assets/patoJuju.png',
};
export function Home(){
const navigation = useNavigation<any>();
const [showBottomSheet, setShowBottomSheet] = React.useState(false);
const [param, setParam] = useState(1);
const hide = () => {
setShowBottomSheet(false)
}
function handleAbout(){
navigation.navigate('About');
}
let skin = 'vovo';
switch(param) {
case 1: skin = 'vovo'; break;
case 2: skin = 'mc'; break;
case 3: skin = 'pato'; break;
}
return /* the rest goes here */
}
To reference the actual image, you would use something like {imagens[skin]}.
I moved imagens outside of this function because it never changes, but it doesn't impact anything otherwise.

How to change icon depending on which array item is pressed in React Native?

I have an array of details on a collapsible component, how can I change the icon chevron-down to chevron-up and vice versa depending on which item on .map() is pressed?
The problem is when I tap on an item all the icons of the other items changes with the state.
How to change state only for an item in array?
Here is my code:
const [iconName, setIconName] = useState("chevron-down")
return (
<AppScreen>
<ScrollView style={styles.container}>
{
terms.map((term, index) => {
return (
<Collapse
key={index}
style={styles.overlayContainer}
onToggle={() => iconName === "chevron-down" ? setIconName("chevron-up") : setIconName("chevron-down")}
>
<CollapseHeader style={styles.collapseHeaderStyle}>
<View style={styles.collapseHeaderStyle}>
<AppText style={styles.title}>{term.title}</AppText>
</View>
<AppIcon iconName={iconName} iconType="ionicon" iconColor={colors.secondary} />
</CollapseHeader>
<CollapseBody style={styles.collapseBody}>
{
terms[index].contents.map((content, index) => {
return (
<React.Fragment key={index} >
<AppText style={styles.content}>{content.content}</AppText>
</React.Fragment>
)
})
}
</CollapseBody>
</Collapse>
)
})
}
</ScrollView>
</AppScreen >
)
you need to modify the terms array and keep track of it. Accoriding to the value returned you can display the icon that you want. here is a basic example of how this can be achieved.
const [iconName, setIconName] = useState("chevron-down")
const [terms, setTerms] = useState([])
const handlePress = (index) => {
const arr = [...terms]
arr[index].collapsed = !arr[index].collapsed
setTerms(arr)
}
return (
<AppScreen>
<ScrollView style={styles.container}>
{
terms.map((term, index) => {
return (
<Collapse
key={index}
style={styles.overlayContainer}
onToggle={() => handlePress(index)}
>
<CollapseHeader style={styles.collapseHeaderStyle}>
<View style={styles.collapseHeaderStyle}>
<AppText style={styles.title}>{term.title}</AppText>
</View>
{/* Display the icon based on true or false */}
<AppIcon iconName={term.collapsed ? "chevron-down" : "chevron-up"} iconType="ionicon" iconColor={colors.secondary} />
</CollapseHeader>
<CollapseBody style={styles.collapseBody}>
{
terms[index].contents.map((content, index) => {
return (
<React.Fragment key={index} >
<AppText style={styles.content}>{content.content}</AppText>
</React.Fragment>
)
})
}
</CollapseBody>
</Collapse>
)
})
}
</ScrollView>
</AppScreen >
)

FlatList not rendering style dynamically

I'm currently struggling in making my FlatList applying the changes I do to it. What I am wanting right now is that when I click an item in my flatlist, that it highlights in a certain color. I followed an approach done by a guy but I am having the problem that to me is not working the update once I click.
I can see through console that all I am doing performs a modification but I think that I am missing some point with extraData parameter since it is not re-rendering with the backgroundColor that I would like to apply.
The code I have is as following, I know that the style I am applying is correct since if i substitute in the map styles.list per styles.selected, everything gets the background I would like to be applied to the elements I click.
So summarizing, the issue I think I have is that the flatlist is not re-rendering so it doesn't show the modifications I perform on it. Any idea of what I am doing wrong? Any tip?
render() {
const { students, studentsDataSource, loading, userProfile } = this.props.navigation.state.params.store;
this.state.dataSource = studentsDataSource._dataBlob.s1.map(item => {
item.isSelect = false;
item.selectedClass = styles.list;
return item;
})
const itemNumber = this.state.dataSource.filter(item => item.isSelect).length;
return (
<View style={styles.container}>
<Item rounded style={styles.searchBar}>
<Input placeholder='Group Name'/>
</Item>
<FlatList
style={{
flex: 1,
width: "100%",
}}
data={this.state.dataSource}
ItemSeparatorComponent={this.FlatListItemSeparator}
renderItem={ ({ item }) => (
<ListItem avatar style={[styles.list, item.selectedClass]}
onPress={() => this.selectItem(item)}>
<Left>
{!item.voteCount && <Avatar unseen={true} /> }
{!!item.voteCount > 0 && <Avatar />}
</Left>
<Body>
<Text>{item.name}</Text>
<Text note>{item.group}</Text>
</Body>
</ListItem>
)
}
listKey={item => item.key}
extraData={this.state}
/>
</View>
);
}
Here we can find the state and SelectItem functions:
constructor(props) {
super(props)
this.state = {
dataSource : [],
}
}
//FlatListItemSeparator = () => <View style={styles.line} />;
selectItem = data => {
//{console.log("inside SelectItem=", data)}
data.isSelect = !data.isSelect;
data.selectedClass = data.isSelect? styles.selected: styles.list;
const index = this.state.dataSource.findIndex( item => data.key === item.key);
this.state.dataSource[index] = data;
this.setState({
dataSource: this.state.dataSource,
});
console.log("This state has the changes:=",this.state.dataSource)
};
Well the main issue was that I was not using the .setState and instead I was doing assignations which killed the listeners.

react-native-elements checkbox update value

I have the following code and for some reason the checkbox is not updated when I click on them. Does anyone know what might be the problem? I am using CheckBox from react-native-elements. The checked property is based on whether a value exists in a set. The onpress function updates the state variable and I am able to get the correct values from the state variable. Thanks!
constructor(props) {
super(props);
this.state = {
interests: new Set(),
brands: new Set(),
medicalCondition: new Set(),
errorMessage: '',
loading: false
}
}
onPressHandler = (event, value, keyName) => {
let tempCheckedValues = new Set(this.state[keyName]);
tempCheckedValues.has(value) ? tempCheckedValues.delete(value) : tempCheckedValues.add(value);
console.log(tempCheckedValues);
this.setState({[keyName] : tempCheckedValues});
}
renderCheckboxGroup = (checkboxList, keyName) => {
return checkboxList.map((value, index) => {
return (
<CheckBox
key={index}
title={value}
onPress={(event) => this.onPressHandler(event, value, keyName)}
checked={this.state[keyName].has(value.toLowerCase())}
/>
)
})
}
render() {
const interestsConst = ["Tennis", "Golf", "Shopping", "Movie", "Hiking", "Reading", "Diving", "Investing"];
const brandsConst = ["Chanel", "Louis Vuitton", "H&M", "ZARA", "Hermes", "Gucci", "Cartier", "Burberry", "Nike", "Adidas", "Lululemon", "Athleta"];
const medicalConditionConst = ["Hypertension", "Hyperlipidemia", "Diabetes", "Back pain", "Anxiety", "Asthma", "Cancer", "Depression", "Shingles"];
return (
<View style={styles.container}>
<ScrollView>
<View style={styles.cardGroup}>
<Card title='Interests'>
{this.renderCheckboxGroup(interestsConst, 'interests')}
</Card>
</View>
<View style={styles.cardGroup}>
<Card title='Brands'>
{this.renderCheckboxGroup(brandsConst, 'brands')}
</Card>
</View>
<View style={styles.cardGroup}>
<Card title='Medical Conditions'>
{this.renderCheckboxGroup(medicalConditionConst, 'medicalCondition')}
</Card>
</View>
</ScrollView>
</View>
)
}
}

Active is not updating. After a hot reload it is active react native

My child component is below
export default function PickerList ({headingText,listData,hideView,finalpickedItem,onItemSelected,selected} ) {
const {modalHolder,modalHeader,modalHeaderText,modalBody,PerListView,PerListVie wText,okCancel,okCancelHolder,PerListViewActive,
} = styles;
return(
<View style={modalHolder}>
<View style={modalHeader}>
<Text style={modalHeaderText}>{headingText}</Text>
</View>
<View style={modalBody}>
<FlatList data={listData} renderItem={({item , index}) =>
<TouchableOpacity
onPress={() => {
{headingText === 'name'?
onItemSelected(item.name)
: headingText === 'Time' ?
onItemSelected(item.time)
: headingText === 'Property'
onItemSelected(item.property)
}
}}
style={{width:'100%',}}
>
<View
style={
selected===item.name ? PerListViewActive : PerListView > // here i am not getting active hot reload making it active
<Text style={PerListViewText}>
{item.name }
</Text></View>
</TouchableOpacity>
}
keyExtractor={(item, index) => index.toString()}
/>
</View>
</View>
);
};
PickerList.propTypes = {
onItemSelected: PropTypes.func.isRequired,
};
and my parent is
onMenuItemSelected = item => {
console.log(item); // i am getting here selected item
this.setState({ commonSelected: item }); // i am getting final state also.
}
<PickerList
headingText="Property"
listData = {this.state.property_type_options}
hideView = {()=>{this.hideView()}}
finalpickedItem = {()=>{this.finalpickedItem()}}
onItemSelected={this.onMenuItemSelected}
selected = {this.state.commonSelected} /// i have final value here also
/>
issue is "selected" not working every thing is working fine .. selected working but after a hot reload. can i re-render module. state is updating fine but it is not getting active.
I found my answer this is very nice.
extraData={this.state}