Sss.
Sss.

Reputation: 53

How to change the color of selected item ReactJS

I have a map function on my app:

list.map((item, index) => {
    return (
       <View key={index}>
           <Text 
               style={ this.state.active ? listStyle.listDone : listStyle.list } onPress={() => this.changeStatus(index)}
           > 
               {item} 
           </Text>
       </View>
    )
})

I want to change the color when the current item i is clicked.

Upvotes: 2

Views: 3218

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104369

Since you want to select multiple items so instead of controlling the elements using single state value, use an array.

Store the selected indexes in the state array, whenever user click on any new item put it's index in that array otherwise remove it, and during ui creation check whether index in present in array or not and on the basis of that specify the color.

How to add or remove elements from array?

For that you need to pass a extra parameter in onClick function "the index of item" and by using that index add/remove elements.

Step1:

Define indexes = [] in state;

Step2:

list.map((item, index) => {
    return (
        <View key={index}>
           <Text 
               style={ this.state.indexes[index] ? listStyle.listDone : listStyle.list } 
               onPress={() => this.changeStatus(index)}> {item} </Text>
        </View>
    )
})

onclick(index) {
    let indexes = this.state.indexes.slice(0);
    if(indexes.indexOf(index) == -1)
        indexes.push(index);
    else{
        let id = indexes.indexOf(index);
        indexes.splice(id, 1)
    }
    this.setState({indexes});
}

See this sample working jsfiddle: https://jsfiddle.net/mayankshukla5031/17h4Lz5u/

Upvotes: 1

Related Questions