Rahul Singh
Rahul Singh

Reputation: 19622

How to Simulate a Keyboard Event in React onClick?

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.

Upvotes: 5

Views: 9200

Answers (2)

karthik vishnu kumar
karthik vishnu kumar

Reputation: 1021

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

Upvotes: -1

Avanish Pai
Avanish Pai

Reputation: 64

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/

Upvotes: 0

Related Questions