Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the TextField value when enter key is pressed in React?

I want to pass TextField values when user press enter key from keyboard. In onChange() event, I am getting the value of the textbox, but How to get this value when enter key is pressed ?

Code:

import TextField from 'material-ui/TextField';  class CartridgeShell extends Component {     constructor(props) {       super(props);       this.state = {value:''}       this.handleChange = this.handleChange.bind(this);    }     handleChange(e) {       this.setState({ value: e.target.value });    }     render(){       return(          <TextField               hintText="First Name"               floatingLabelText="First Name*"              value={this.state.value}               onChange={this.handleChange}               fullWidth={true} />       )    } } 
like image 894
Soumya Behera Avatar asked Apr 13 '17 05:04

Soumya Behera


People also ask

How do you get the value of textfield in React?

To get the value of an input field in React:Use event. target. value to get the input field's value and update the state variable.

How do you use Enter key in React?

To submit a form using the Enter key in React: Add a button element with type set to submit . Add an onSubmit prop that points to a submit handler function. Every time the user presses Enter, the handle submit function will be invoked.

How do you trigger a click event on pressing Enter key React?

Using the onKeypress event The onKeyPress event is fired when a user presses the key on a keyboard, so that by using this we can trigger the button click by pressing a Enter key. The keyCode for the Enter key is 13.


1 Answers

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.

like image 195
Mayank Shukla Avatar answered Sep 17 '22 15:09

Mayank Shukla