Next.js Discord

Discord Forum

Originally-disabled button not working when "disabled" property is removed

Answered
Batimius posted this in #help-forum
Open in Discord
Hello there. Just like the title says, I have a button which I initially apply the disabled attribute. However, when I remove this attribute later on, the onClick continues to refuse to work. I'll post the code in the message below. Ultimately, if I return the component with the disabled attribute in the button, even if it is later removed by code, the onClick will not work. On the other hand, if I don't apply the disabled attribute by default and apply it later, it will work as intended when it is later removed. I don't know if this is a React bug or a Next.js bug, but any information is helpful. Thank you for your time and help!
Answered by Batimius
Looks like this is a React error, and it looks like it is intentional. More info here: https://github.com/facebook/react/issues/12704
View full answer

2 Replies

'use client'

import React, { useState, useRef } from 'react'
import './EntryContainer.css'
import SongEntry from './SongEntry'

export default function EntryContainer() {
    const buttonRef = useRef(null)
    const [selected, setSelected] = useState(null) as [null | HTMLButtonElement, React.Dispatch<React.SetStateAction<null | HTMLElement>>]

    const handleSongClick = (clickEvent: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
        const nextButton = buttonRef.current as unknown as HTMLButtonElement

        if (selected) {
            selected.parentElement?.removeAttribute("selected")
            selected.innerText = "Select"
        }

        const target = clickEvent.target as HTMLButtonElement
        if (target == selected) { setSelected(null); nextButton.setAttribute("disabled", ""); return }

        target.parentElement?.setAttribute("selected", "")
        target.innerText = "Selected"
        setSelected(target)

        nextButton.removeAttribute("disabled")
    }

    const handleNextClick = (clickEvent: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
        console.log("Yo?")
        const res = fetch("/api/songs")
    }

    return (
        <>
            <div className="entry-container">
                <SongEntry key="1" title="JJK S2 OP2" name="SPECIALZ" artist="King Gnu" embedId="5yb2N3pnztU" handleClick={handleSongClick}></SongEntry>
                <SongEntry key="2" title="JJK S1 OP1" name="Kaikai Kitan" artist="Eve" embedId="GwaRztMaoY0" handleClick={handleSongClick}></SongEntry>
            </div>
            <div className="button-holder">
                <button ref={buttonRef} onClick={handleNextClick} className="primary-button" disabled>Next</button>
            </div>
        </>
    )
}
Looks like this is a React error, and it looks like it is intentional. More info here: https://github.com/facebook/react/issues/12704
Answer