Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

193
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda