There is a list of nav items and its focus nav item below each press TAB key, I need to fire the onClick event of the focused nav item when pressing the ENTER key.
This is what I do,
onKeyPress works as expected but do not trigger onClick
NavBar compoenent:
const Navbar = () => {
...
return (
<nav>
<ul style={{ listStyleType: 'none', padding: 0, margin: 0 }}>
{authenticatedRoutes.map((currentItem: any, index: number) => {
const isOpen = openedDrawer === currentItem.path
return (
<ul
key={`ROUTE_LIST_${index}`}
style={{
listStyleType: 'none',
}}
>
<li key={`ROUTE_${index}`}>
<div
onKeyPress={e => {
if (e.key === 'Enter') {
const event = new MouseEvent('click')
e.target.dispatchEvent(event)
}
}}
onClick={() => {
history.push(currentItem.path)
}}
role="link"
tabIndex={0}
>
<div style={{ display: 'flex', alignItems: 'center' }}>
<div
style={{
...LEFT_BORDER,
backgroundColor: isOpen ? 'transparent' : 'initial',
}}
/>
{linkText}
</div>
</div>
</li>
</ul>
)
})}
</ul>
</nav>
)
You can't programatically trigger native event hooks on a component easily in react.
The best solution would be to put the code in your onKeyPress
as well...
onKeyPress={e => {
if (e.key === 'Enter') {
history.push(currentItem.path) // I Added this line
const event = new MouseEvent('click')
e.target.dispatchEvent(event)
}
}}
onClick={() => {
history.push(currentItem.path)
}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.