Next.js fails to update the user interface (UI) when there is a change in

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);
}

Answer №1

The issue lies in attempting to pass data within a JSX element as if it were in standard html format.

data-amenity={data}

React operates differently than this. As a result, e.currentTarget.dataset.amenity will always be undefined. Instead, React utilizes refs to interact with DOM elements. Further information on refs can be found in the official React documentation. However, in your specific case, there is no need for a ref, as you can directly send data to any function. See below:

<div 
    className={`amenity ${active && `amenity-active`}`} 
    key={data} 
    // data-amenity={data}
    onClick={() => addAmenity(data)}
    >
    <p>{text}</p>
</div>

In the addAmenity function, simply receive the data like so:

const addAmenity = (incoming) => {
    let dataItem = incoming
    ...
}

Below, you'll find the corrected version of your code that functions perfectly. Feel free to reach out if you found this helpful.

//Next js
import { useState } from 'react'
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 AddDorm = () => {
    const [amenitiesList, setAmenitiesList] = useState(amenitiesDefaultArr)

    const addAmenity = (incoming) => {
        let dataItem = incoming

       const tempList = amenitiesList.map(el => {
            if (el.data === dataItem) el.active = !el.active
            return el
        })

        console.log(tempList)
        setAmenitiesList(tempList)
    }

    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={() => addAmenity(data)}
                 >
                    <p>{text}</p>
                    {icon}
                </div>
           )})}
      </> 
    )
}

export default AddDorm

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you quickly navigate to the top of the page before clicking on a link in the same window/tab?

Could someone assist me with a coding issue I am facing? I would like to be able to go to the top of the page when clicking on a link and have the link open in the same tab. I attempted to implement this functionality using the following code, however, I ...

What is the best way to implement a new token/session in next-auth server-side after customizing the signOut method?

Using Next-Auth's credentials provider, the user is signed in by setting their information into a token and then into a session. Cookies are also set. To sign out, I customized the default signOut Method [...nextauth].ts events: { async signOut( ...

Incorporating Computer Modern Serif into Your Jekyll GitHub Page

I have customized a version of the Jekyll GitHub page from here and am trying to incorporate Computer Modern Serif font as the main body font across all pages. Following instructions from an informative answer, I have downloaded the necessary files from th ...

Leveraging the local variables within a function in conjunction with the setTimeout method

Currently, I'm facing an issue with a website that I'm working on. I have created a function that should add a specific class to different ids in order to make images fade out one by one on the home page. To streamline the process, I used a local ...

Having trouble getting my image to appear at the top of the website, could it be an alignment issue?

Here is a screenshot showing the issue: https://i.stack.imgur.com/kSVQj.png. The quote on my website does not align to the top as expected. Can anyone provide a solution for this? Below is the corresponding code: <body> <div id="container"> ...

Pattern to locate a CSS class identifier

I've been working on creating a regex to match valid CSS class name structures. Currently, my progress looks like this: $pattern = "([A-Za-z]*\.[A-Za-z]+\s*{)"; $regex = preg_match_all($pattern, $html, $matches); However, there are certai ...

Error: The type 'boolean | (() => void)' cannot be assigned to type 'MouseEventHandler<HTMLButtonElement> | undefined'

Playing audio in a NextJS app while writing code in TypeScript has been an interesting challenge. The onClick() function performs well in the development environment, triggered by npm run dev. <button onClick ={toggle}> {playing ? "Pause" : ...

CSS - setting all child elements to the height of the tallest child element

Is there a way to ensure that both fieldsets have the same height as the tallest one? See the code snippet below or visit this link for reference: http://jsfiddle.net/zpcXQ/2/ <div id="parent"> <form> <fieldset id="left"> ...

Tips for eliminating the horizontal scroll bar on a responsive background image

I'm having an issue with a full-width div containing a background image on my responsive website. Everything looks fine on desktop, but when I switch to responsive mode using Chrome Dev Tools, a horizontal scroll bar appears that I can't remove w ...

Creating a billing portal link for Stripe within a NextJS application using the Firebase extension

In my NextJS web app, I am utilizing the Stripe extension in Firebase to manage subscriptions. My objective is to generate a link for returning users to modify their payment information on Stripe without the need for re-authentication since they are alread ...

Troubleshooting connectivity problems: SocketIO integration with microservices on a Kubernetes platform

I have organized my system using microservices architecture, with separate services for client interactions, orders, payments, and more. Each of these services runs on its own express server. Now, I am looking to integrate real-time feedback functionality ...

Click to expand for answers to commonly asked questions

Having trouble setting up a FAQs page on my blog and can't seem to get the code right. Check out what I'm trying to do here: http://jsfiddle.net/qwL33/ Everything seems fine but when I click on the first question, both questions open up. Can som ...

How to Display HTML Content from a WYSIWYG Editor in ASP.NET Webforms without Master Page Bootstrap Styles Interfering

I am facing an issue in ASP.NET Webforms with a Master Page that imports Bootstrap CSS, which is then used by all child pages of the site. One of the child pages contains HTML content generated from a WYSIWYG editor. However, the styles applied by Bootstr ...

Disabling the 'fixed navigation bar' feature for mobile devices

Here's a code snippet that I'm working with. It has the ability to make the navigation stick to the top of the page when scrolled to. HTML <script> $(document).ready(function() { var nav = $("#nav"); var position = nav.position(); ...

How can I implement a toggle button to display additional details for a specific row within a table created using React.js?

I'm currently working on a project using Next.js and have come across an unexpected issue. Upon reading a JSON file, I populate a table with the data retrieved from it. Each piece of information in the table has hidden details that should only be reve ...

Use Javascript to display an image based on the date, otherwise hide the div

I'm looking to implement an image change on specific dates (not days of the week, but actual calendar dates like August 18th, August 25th, September 3rd, etc). Here's the div I'm working with: <div id="matchday"> <img id="home ...

Learn how to easily center a responsive navbar using Twitter Bootstrap

I'm having a bit of trouble creating a website with Twitter Bootstrap, specifically when it comes to centering the navigation links in responsive design. My goal is to have a two-row navigation bar for tablet and phone devices, with the brand name at ...

Tips for using jQuery to add or append a class to the final li element

I am currently struggling to understand why the last child of the li element is not being inserted into the last li. This module functions as a treeview, and my main objective is to add a class to the last li. Let me demonstrate with some sample code and ...

The implementation of @font-face is failing to display on all currently used web browsers

Hey there, I could really use some help with getting @font-face to work properly. Despite trying numerous solutions, I still seem to be missing something. If anyone can spot what I'm doing wrong, please let me know! @font-face { font-family: " ...

Delete unnecessary css code

After years of working on a website, it has grown significantly in size. The CSS files have become quite messy and unclear. I need to figure out how to identify which parts of my extensive CSS file are not being utilized on my homepage so that I can safel ...