Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enter key event handler on react-bootstrap Input component

I have an Input component with a button (buttonAfter property), I set an onClick handler associated to the button and so user can type some text and clic the button to fire the right action.

However, I would like user to be able to press [Enter] key (keycode 13) to achieve the same effect as clicking on the button, just to make the UI easier to use.

I could not find a way to do it, of course I tried onKeydown to register an handler for key down event but it is just ignored.

like image 362
mguijarr Avatar asked Dec 11 '15 12:12

mguijarr


People also ask

How do you write a keypress event in React?

To handle key presses in React, we use onKeyPress. It is passed as an attribute in <input> elements, and can be used to perform actions for any event involving the keyboard, whether you want to call a function on any key press, or only when a specific key is pressed.


1 Answers

I think this question is related to React itself instead of react-bootstrap.

Look at this for some basics about React event system: https://facebook.github.io/react/docs/events.html

When you use onKeyDown, onKeyPress or onKeyUp React will pass to your handler an instance of say "target" object with the following properties:

boolean altKey
number charCode
... (for all see link above)

So you can do something like this:

import React, { PropTypes } from 'react'; import ReactDOM from 'react-dom'; import { Input } from 'react-bootstrap';  class TestInput extends React.Component {  handleKeyPress(target) {   if(target.charCode==13){     alert('Enter clicked!!!');       }  }  render() {   return (     <Input type="text" onKeyPress={this.handleKeyPress} />   );  } }  ReactDOM.render(<TestInput />, document.getElementById('app')); 

I tested above code and it works. I hope this is helpful for you.

like image 89
baudo2048 Avatar answered Oct 06 '22 00:10

baudo2048