Enter key event handler on react-bootstrap Input component

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.


The question can also be related to React-bootstrap. React-bootstrap also has a way to handle instance when ever a button or enter key or any form element is pressed.

The below code explains how to handle an instance when enterkey is pressed without the involvement of React Handlers.(and that makes it cool)

import React from "react";
import ReactDOM from "react-dom";
import { FormGroup, FormControl } from "react-bootstrap";

class TestInput extends Component {

  search() {
    console.log("Enter Button Pressed");
  }

  render() {
    return (
      <FormGroup>

        <InputGroup>
          <FormControl
            placeholder="Press Enter"
            type="input"
            onKeyPress={event => {
              if (event.key === "Enter") {
                this.search();
              }
            }}
          />
        </InputGroup>

      </FormGroup>
    );
  }
}

React Bootstrap does not support Input form element anymore. Instead it introduced below items at your disposal

The FormGroup component wraps a form control with proper spacing, along with support for a label, help text, and validation state.

Wrap your form control in an InputGroup, then use for normal add-ons and for button add-ons.

The FormControl component renders a form control with Bootstrap styling.

References:

https://react-bootstrap.github.io/components.html#forms https://react-bootstrap.github.io/components.html#forms-input-groups