Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Material-ui component onKeyUp event is not triggering

I have a material-ui component Grid and I have a onKeyUp event on that
But somehow onKeyUp is not triggering

<Grid item xs={12} onKeyUp={handleClickOnKeyUp} sx={{cursor: "pointer"}} onClick= 
  {handleClickGrid}>
</Grid>

and the functions are

const handleClickOnKeyUp = () => {
  console.log("123123123");
}

const handleClickGrid = () => {
   console.log("456456456");
}

Other code for Grid and Grid items under Grid container is working fine, There is no problem in that
The onClick event is also working but onKeyUp is not working
What is the issue ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to add a tabIndex to the component (element) to allow it to accept focus. For example:

<Grid
  item
  xs={12}
  onKeyUp={handleClickOnKeyUp}
  sx={{ cursor: "pointer" }}
  onClick={handleClickGrid}
  tabIndex={0} {/* tabIndex added here */}
>
...
</Grid>

Updated answer to additional comment:

If you’d also like to remove the focus outline, you can add the styling:

<Grid
  item
  xs={12}
  onKeyUp={handleClickOnKeyUp}
  sx={{ cursor: "pointer", "&:focus": { outline: "none" } }} {/* removes focus outline */}
  onClick={handleClickGrid}
  tabIndex={0}
>

Working CodeSandbox: https://codesandbox.io/s/pensive-leaf-x4e6xv?file=/demo.js

Note: If you are concerned about accessibility, I’d be careful setting that tabIndex property to anything other than zero (0).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading