how do i access event and value passed to function at a time here is what i have tried
<ul className="list" data-testid="lists">
{options.map((option, i) => (
<li
role="button"
tabIndex="0"
onClick={() => {
setSelected(option);
setOpen(false);
}}
className={state.cursor === i ? "activeList" : "list-item"}
onKeyDown={ handleEnter(option) }
>
{option}
</li>
))}
</ul>
const handleEnter = (option, e) => {
if (e.keyCode === 13) {
setSelected(option)
}
};
what i want to do is when enter pressed want to update the state with value of option but not able to do so what should i do
The event object is passed into the onXXX function.
If you want to pass it from the onKeyDown function to the handleEnter function then you must do so explicitly.
You also have to pass a function to onKeyDown in the first place, not undefined which is the return value of the function you are calling.
Use useCallback to stop the function being recreated on every render.
const onKeyDown = useCallback(
(event) => handleEnter(option, event),
[option, handleEnter]
);
and
onKeyDown={ onKeyDown }
Do note, however, that keyCode is deprecated and we have better alternatives for it now.
You can update the property like
onKeyDown={(e)=> handleEnter(option, e)}
it will bind your events in your handleEnter function. I hope it will work for you. Thanks.