Home > Net >  e.target.disabled = true doesn't work if a useState Hook is present in the same function
e.target.disabled = true doesn't work if a useState Hook is present in the same function

Time:10-15

I have two tables next to each other. The table to the left contains an add button that passes content from the left table to the right table.

Once this process is done, the button must become disabled and it should inherit a different style from a different class.

const [recordsRight, setRecordsRight] = useState([]);

<TableBody className = "leftTable">
    {
        recordsLeft === null ?
        []
        :
        recordsLeft.map((item, index) => (
            //<TableCell></TableCell> //Table Contents
            <button className="addToggle" id={"addToggle"   index} onClick={(e) => handleAddSwitch(e, item)}>
                <CircleCheckIcon />
                Add
            </button>
        ))
    }
</TableBody>

<TableBody className = "rightTable">
    {
        recordsRight === null ?
        []
        :
        recordsRight.map((item, index) => (
            //<TableCell></TableCell> //Same Table Contents
        ))
    }
</TableBody>

function handleAddSwitch(e, item) {
    e.target.disabled = true;
    e.target.className = "addToggle2";
    
    let newRecordsRight = [...recordsRight];
    newRecordsRight.push(item);
    setRecordsRight(newRecordsRight);
    
}

.addToggle{
    background: green;
}

.addToggle2{
    background: grey;
}

when I remove the setRecordsRight line from the handleAddSwitch function, the color of the button changes and it becomes disabled.

But once I add it again, the process stops working and I would be able to add the same item from left to right over and over again. What should I do?

CodePudding user response:

You should be storing the flag for disabled/enabled in your component state (as a flag on item, or as a separate map of flags keyed by some unique identifier for item), not directly modifying the DOM. (This doesn't just apply to the disabled flag on buttons, it applies generally to anything in the rendered DOM.) The reason is that if you directly modify the DOM, then your component is re-rendered for any reason, React will overwrite your DOM modifications.

Here's a simplified example:

  • Related