Home > database >  React identify control or shift key pressed
React identify control or shift key pressed

Time:10-21

I am rendering a table as follows

<div>
   <table>
     <tbody>
          {students.map(x)=> ( <tr onClick{(e)=>selectStudent(i)} ={><td>{x}</td></tr>)}
     </tbody>
   </table>
</div>

Row click is working fine. My question how to capture control and shift keys along with mouse click?

CodePudding user response:

You need to check if the click event has registered those keys being pressed.

This article describes the process:

    onClick={e => {
      if (e.ctrlKey || e.metaKey) return onCmdControlClick(e);
      onClick(e);
    }}

CodePudding user response:

You can capture keyboard events such as onKeyDown, onKeyPress, onKeyUp.

 const keyboardEventHandler = (e) => {
    if (e === "Shift") {
      // do something
      console.log("Shift is pressed");
    } else {
      console.log(`${e} is pressed`);
    }
  };
return(
<input onKeyDown={(e) => keyboardEventHandler(e.key)} type="text"/>
)

Working Demo

  • Related