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

191
Visualizações
React useState: Toggle boolean attribute inside object - how to identify onClick source?

This may be a simple question and I'm just missing something, but I haven't found an answer yet.

I would like to use useState with an object storing both onChange and onClick events.

With onChange, the attributes of event.target.name and event.target.value are provided from the virtual DOM. That makes it easy to identify which parameter the event should be targeting.

However, with onClick there is no attribution of the element from either of these event.target parameters.

How can one identify which tag is generating an onClick event in order to tell the handler which parameter it should affect in an object of several boolean parameters?

Here's an example I created in an effort to be both as simple and complete as possible:

import React from 'react';

const initialState = {
    switches: {
        menuOpen: false,
        modalOpen: false,
    },
    fields: {
        username: '',
        password: '',
    },
};

export default function Header(props) {
    const [changeStateObj, setChangeStateObj] = useState(initialState.fields);
    const [toggleStateObj, setToggleStateObj] = useState(initialState.switches);

    useEffect(() => {
        console.log(changeStateObj, toggleStateObj);
    }, [changeStateObj, toggleStateObj]);

    const changeHandler = (event) => {
        let name = event.target.name;  // these provide values
        let value = event.target.value;
        setChangeStateObj((values) => ({ ...values, [name]: value })); // and therefore, this works
    };

    const clickHandler = (event) => {
         let name = event.target.name  // nothing here
        setToggleStateObj((prevState) => ({ [name]: !prevState.name }));  // no dice
    };

    return (
        <div>
            <label htmlFor="username">
                User Name
                <input type="text" name="username" onChange={changeHandler} />
            </label>
            <label htmlFor="password">
                Password
                <input type="password" name="password" onChange={changeHandler} />
            </label>
            <button name="modalOpen" onClick={clickHandler}>
                Open modal
            </button>
            <button name="menuOpen" onClick={clickHandler}>
                Open menu
            </button>
        </div>
    );
}

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

0

const handleClickModalOpen = () => clickHandler({target: {name : 'modalOpen'}});

<button name="modalOpen" onClick={handleClickModalOpen}>
    Open modal
</button>

Second approach, with your existing code, try use event.currentTarget.name rather than event.target.name. The currentTarget should tell you which exact element you've attached the event handler.

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