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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad