Home > Blockchain >  Material-ui component onKeyUp event is not triggering
Material-ui component onKeyUp event is not triggering

Time:12-14

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 ?

CodePudding user response:

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

  • Related