In my latest Next.js project, I am working on a feature that involves looping through an array of amenities. Each amenity is displayed in a div element that, when clicked, toggles the active property. The logic behind this functionality is handled by the addAmenity function, which iterates through the amenities array and toggles the active property of the specific item accordingly. However, despite the console.log(tempList) confirming the change in state, the UI does not reflect this by showing a green background color for the div with an active status. Any ideas on what might be causing this issue?
//Next js
const amenitiesDefaultArr = [
{
data: "bathroom",
text: "Private Bathroom",
icon: <WcIcon fontSize="large" />,
active: false,
},
{
data: "dining",
text: "Dining Hall",
icon: <FastfoodIcon fontSize="large" />,
active: false,
},
{
data: "wifi",
text: "Wifi",
icon: <WifiIcon fontSize="large" />,
active: false,
}
]
const addAmenity = (e) => {
let dataItem = e.currentTarget.dataset.amenity
let tempList = amenitiesList
tempList.map(el => {
if (el.data === dataItem) el.active = !el.active
return el
})
console.log(tempList)
setAmenitiesList(tempList)
}
const AddDorm = () => {
const [amenitiesList, setAmenitiesList] = useState(amenitiesDefaultArr)
return (
<>
{
amenitiesList.map(el => {
const {data, text, icon } = el
let { active } = el
return (
<div
className={`amenity ${active && `amenity-active`}`}
key={data}
data-amenity={data}
onClick={(e) => addAmenity(e)}
>
<p>{text}</p>
{icon}
</div>
)
</>
})
)
/* CSS */
.amenity {
padding: 0.5rem 1rem;
display: flex;
align-items: center;
border-radius: 50px;
box-shadow: 5px 5px 10px #919191,
-5px -5px 10px #ffffff;
z-index: 4;
cursor: pointer;
}
.amenity-active {
background-color: var(--green);
}