Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

428
Visualizações
e.target.disabled = true doesn't work if a useState Hook is present in the same function

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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:

const {useState} = React;

let nextItemId = 1;
const initialItems = [
    {id: nextItemId++, enabled: true},
    {id: nextItemId++, enabled: true},
    {id: nextItemId++, enabled: true},
    {id: nextItemId++, enabled: true},
];
const Example = () => {
    const [items, setItems] = useState(initialItems);
    
    const addItem = () => {
        setItems(items => [...items, {
            id: nextItemId++,
            enabled: true,
        }]);
    };
    
    const toggleItem = itemToToggle => {
        setItems(items => items.map(item => {
            if (item.id === itemToToggle.id) {
                item = {...item, enabled: !item.enabled};
            }
            return item;
        }));
    };
    
    return <div>
        {items.map(item => (
            <div className="item" key={item.id} onClick={() => toggleItem(item)}>
                Item {item.id}: {item.enabled ? "Enabled - click to disable" : "Disabled - click to enable"}
            </div>
        ))}
        <input type="button" onClick={addItem} value="Add item" />
    </div>;
};

ReactDOM.render(<Example />, document.getElementById("root"));
.item {
    user-select: none;
}
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda