3

I am Currently in process of Developing a on screen handler for my Web application using React and i am facing some problem in creating events for backspace and arrow on screen keys.

I have a layout like this

enter image description here

I was looking at a coupler of questions which used jquery but i also came across multiple SO questions which said its a bad practise to use jquery with React because of the virtual DOM concept react uses .

How to trigger backspace on a textfield?

How to use JQuery with ReactJS

How do i simulate the events of backspace and arrow left and right buttons from the onscreen controls using React or pure JS.

Update

I donot want to have to trigger the on screen button based on keypress, its the other way around. I want to click the onscreen button which trigger the event for the keyboard press automatically and does the necessary event on input.

Rahul Singh
  • 19,030
  • 11
  • 64
  • 86
  • If you are using redux or any other state management system, all you have to do is dispatch an action. If not, you can try to register a keypress event on container and then using refs, call click of that button – Rajesh Sep 18 '19 at 06:27
  • @Rajesh I want it independent of redux just on component level i want this functionality . can you elaborate your comment a bit more – Rahul Singh Sep 18 '19 at 06:29
  • Idea is to have a unified way to handle stuff. So since you have button clicks, you can trigger of necessary button based on keypress using refs. Somethinhg like `this.refs.button_backspace.click()` – Rajesh Sep 18 '19 at 06:36
  • @Rajesh I think you are getting it a bit wrong, I donot want to have to trigger the on screen button based on keypress, its the other way around. I want to click the onscreen button which trigger the event for the keyboard press automatically – Rahul Singh Sep 18 '19 at 06:41

2 Answers2

0

Try to dispatch a KeyboardEvent with corresponding keycodes for from the onClick handler of each of these buttons. You would find the keycodes here https://keycode.info/

-1

Once you capture the Backspace key click event which you showed on the UI. You can try dispatching an event like this .Try using this code inside your click handler.

// keycode 32 is for space event
// keycode 8 is for backspace event

var backspaceEvnt = new KeyboardEvent('keydown' : {'keyCode': 8, 'which': 8});
var spaceEvnt = new KeyboardEvent('keydown' : {'keyCode': 32, 'which': 32});
document.dispatchEvent(backspaceEvnt);
document.dispatchEvent(spaceEvnt);
Roman Mkrtchian
  • 2,548
  • 1
  • 17
  • 24
  • 1
    FYI that should be two arguments, now a key value pair. `new KeyboardEvent('keydown', {'keyCode': 8, 'which': 8})` should work instead. – alex Oct 07 '21 at 21:23