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>
);
}
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.