Ad

How To Properly Add An Event Lister To An Input When Using React

I want to add an event lister to an input, so that when a user is focused on the input and presses Enter, a function of my choice is ran.

I know how to do this with regular javascript but could not find reference to the proper setup in the React documentation.

JS:

const input = document.getElementById("myInput");

input.addEventListener("keydown", function(e) {
  if (e.keyCode === 13) {
    e.preventDefault()
    this.handleEnterPress
  }
})

React Mockup:

class Example extends React.Component {

handleEnterPress = () => {
// some more code here
}

render () {
return(
<input id='myInput'/>
)
}

export default Example
Ad

Answer

Just use onKeyUp:

class Example extends React.Component {

handleKeyPress = e => {
  if (e.which === 13) {  // <-- Enter
     // enter code here
  }
}

render () { 
   return ( <input type="text" id='myInput' onKeyUp={handleKeyPress}/> )
}

export default Example

Some notes about the key events just in case you would care about other than Enter in the future:

KeyPress ignores delete, arrows, home/end, ctrl, alt, shift etc while KeyDown and KeyUp don't

Ad
source: stackoverflow.com
Ad