Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger keypress event in React.js

I'm new to React.js. I'm trying to trigger keypress event for text div.

Here is text box code for which I want to execute keypress trigger.

<div id="test23" contenteditable="true" class="input" placeholder="type a message" data-reactid="137">Hii...</div> 

and keypress method is:

onKeyPress: function(e) {    return "Enter" == e.key ? "Enter key event triggered" : void 0) } 

I tried it with jQuery but I can't trigger it.

Here is my React code that I tried but its not working:

var event = new Event('keypress', {  'keyCode' : 13,  'which' : 13,  'key' : 'Enter' }); var node = document.getElementById('test23'); node.dispatchEvent(event); 
like image 982
Piyush Avatar asked Jan 23 '15 03:01

Piyush


People also ask

How do you trigger a keypress event React?

If you're trying to create a keyboard event, you can make use of KeyboradEvent constructor. An enter key event can be dispatched like: const event = new KeyboardEvent('keypress', { key: 'enter', }); console. log(event) // KeyboardEvent {isTrusted: false, key: "enter", code: "", location: 0, ctrlKey: false, …}

How do you trigger a click event on pressing enter key React?

Using the onKeypress event The onKeyPress event is fired when a user presses the key on a keyboard, so that by using this we can trigger the button click by pressing a Enter key. The keyCode for the Enter key is 13.

How do you know if a keypress is in React?

To detect Esc Key Press in React, we can add an event listener for the keydown event. to define the escFunction function. We check if event. keyCode is 27.


1 Answers

If you create a reference to the div, then you can trigger an event on it. With hooks, you can use useRef. Without hooks, you can use createRef.

With hooks:

function MyComponent() {   const ref = useRef();    // This is simply an example that demonstrates   // how you can dispatch an event on the element.   useEffect(() => {     ref.dispatchEvent(new KeyboardEvent('keypress', {       key: 'Enter',     }));   }, []);    return (     <div       ref={ref}       id="test23"       contentEditable={true}       className="input"       placeholder="type a message"       data-reactid="137"     />   ); } 

Without hooks:

class MyComponent extends React.Component {   constructor(props) {     super(props);     this.ref = React.createRef();   }    // This is simply an example that demonstrates   // how you can dispatch an event on the element.   triggerKeyPress() {     this.ref.dispatchEvent(new KeyboardEvent('keypress', {       key: 'Enter',     }));   }    render() {     return (       <div         ref={this.ref}         id="test23"         contentEditable={true}         className="input"         placeholder="type a message"         data-reactid="137"       />     );   } }  el.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'})); 
like image 118
Matt Huggins Avatar answered Sep 20 '22 12:09

Matt Huggins