I am working on an app that allows the user to select a vehicle from a list. The problem I am having at the moment is that when I try to map the vehicles to a list and select a single vehicle to set a class to, all of the other items in that list are also being set with the same class. Following is the code structure I am having issues with:
The expected outcome of this code is to be able to set a single border around a clicked item in a mapped set of objects. I have attempted a couple different ways of setting this, including trying to exclude all other non-clicked id’s, setting to the name of the item instead of the ID, and using false/true to set the state instead of the ID.
Dummy data to populate the map:
const tempMapObjects = [
{ id: 0, name: 'placeholder 1', vehicle: Vehicle1, alt: 'vehicle 1' },
{ id: 1, name: 'placeholder 2', vehicle: Vehicle2, alt: 'vehicle 2' },
];
Setting the initial state:
const [selectedIdClass, setSelectedIdClass] = useState(0);
Handler:
const handleClickedVehicle = (id) => {
console.log("reached handle Click")
setSelectedIdClass(!id)
}
Map:
{tempMapObjects.map((obj) => { return ( <div className={selectedIdClass ? style['Card2'] : style['Card']} key={obj.id}> <a className={style['ALink']} onClick={(e) => ( handleClickedVehicle({ id: obj.id }) <img className={style['ImgDimensions']} src={obj.vehicle} alt={obj.alt} /> <h6 className={style['StyleVehicleBox']}> {obj.name} </h6> </a> </div> ) })}
How can I set only the state of the currently clicked item in the map list, and not highlight the others?