Reputation:
I am trying to put style on the selected div onClick
let woods = pageURL.map( (wood, key)=> {
if(wood.internal_doors_style[0] === this.state.slug_style) {
if(this.state.selected) {
sel = 'red'
}
return (
<div style={{background: sel}} key={wood.id} className="menu-item wood-item filter-wood" id={wood.id} onClick={()=> this.setW(wood.internal_doors_wood[0])}>
<img src={wood.acf.wood_image.url} alt="" width="40"/>
<span className="span">{wood.acf.woods_title}</span>
</div>
)
}
})
the problem I am having that the style is applying on all the element not the selected one only.
this.setState({
slug_wood: w,
selected: !this.state.selected
})
return single_data = <SingleInternal wood={this.state.slug_wood} style={ this.state.slug_style}/>
}
is there a way maybe to target the id of each element where I set the id of each element to be unique id={wood.id}
Upvotes: 0
Views: 869
Reputation: 5466
Store the id of the selected element in the state variable
and every time you select an element change the state variable
to the selected id
then inside the map check if the value of the selected id is equal to the element id or not if yes then set the selected element style otherwise set the style to unset. Considering selectedId
to be the name of the state variable and onClick setState
:
let woods = pageURL.map( (wood, key)=> {
let sel=unset
if(this.state.selectedId === wood.id){
sel = 'red'
}
return (
<div style={{background: sel}} key={wood.id} className="menu-item wood-item filter-wood" id={wood.id} onClick={()=> this.setState({selectedId: wood.id})}>
<img src={wood.acf.wood_image.url} alt="" width="40"/>
<span className="span">{wood.acf.woods_title}</span>
</div>
)
}
})
Upvotes: 1