Reputation: 1
I have a ListItem in my react website. What event should be triggered to call a function when I press enter
key on focused item.
Code for the ListItem
is as below:
<ListItem
tabIndex={'0'}
className={classes.listItem}
key={timeline}
value={timeline}
onClick={props.handleChangeTimeline}
onKeyDown={handleChange}>
{timeline}
</ListItem>
The onClick
event works fine with mouse click. But I am looking for keyboard accessibilty. So when an element in the dropdown is focused and I press the enter
key a function to handle that event will be called.
I tried onKeyDown
event. It gets triggered but event.target.value
is null. If get this value on some event I think the problem will be solved.
Upvotes: 0
Views: 125
Reputation: 17397
The keydown event would be the way to go. Here's a working example. Perhaps the issue is elsewhere in your code.
function App () {
function listenForEnterKey(event, data) {
if (event.key !== 'Enter') return;
console.log(data)
}
return (
<ul>
<li tabIndex="0" onKeyDown={()=>listenForEnterKey(event, 1)}>Focus and press ENTER.</li>
<li tabIndex="0" onKeyDown={()=>listenForEnterKey(event, 2)}>Focus and press ENTER.</li>
</ul>
)
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
<div id="root"></div>
Upvotes: 0