score:124

Accepted answer

use onkeydown event, and inside that check the key code of the key pressed by user. key code of enter key is 13, check the code and put the logic there.

check this example:

class cartridgeshell extends react.component {

   constructor(props) {
      super(props);
      this.state = {value:''}

      this.handlechange = this.handlechange.bind(this);
      this.keypress = this.keypress.bind(this);
   } 
 
   handlechange(e) {
      this.setstate({ value: e.target.value });
   }

   keypress(e){
      if(e.keycode == 13){
         console.log('value', e.target.value);
         // put the login here
      }
   }

   render(){
      return(
         <input value={this.state.value} onkeydown={this.keypress} onchange={this.handlechange} fullwidth={true} />
      )
    }
}

reactdom.render(<cartridgeshell/>, document.getelementbyid('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


<div id = 'app' />

note: replace the input element by material-ui textfield and define the other properties also.

score:0

html

<input id="something" onkeyup="key_up(this)" type="text">

script

function key_up(e){
    var enterkey = 13; //key code for enter key
    if (e.which == enterkey){
        //do you work here
    }
}

next time, please try providing some code.

score:1

<input onkeypress={onkeypress}/> 

const onkeypress = (e: any) => { if (e.which == 13) { // your function }};

score:4

you can use e.target.value to get the current value of the input element if you're using uncontrolled mode.

<textfield
  onkeypress={(e) => {
    if (e.key === 'enter') {
      alert(e.target.value);
    }
  }}
/>

live demo

codesandbox demo

score:63

adding onkeypress will work onchange in text field.

<textfield
  onkeypress={(ev) => {
    console.log(`pressed keycode ${ev.key}`);
    if (ev.key === 'enter') {
      // do code here
      ev.preventdefault();
    }
  }}
/>

Related Query

More Query from same tag