Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger onblur event on click of enter keypress in React js

I have an input text field . When a user inputs any text and clicks enter button I need to activate the blur event to remove the focus and also to validate the textinput .

<input type="text" 
    style={{marginTop:'20%', marginLeft:'40%'}} 
    value={value} 
    onFocus={onFocus}
    onChange={e => setValue(e.target.value)}
    onKeyPress={handleKeyPress}
/>
like image 981
ReNinja Avatar asked May 20 '19 08:05

ReNinja


People also ask

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.

How do you get the enter key event in React JS?

Let us create a React project and then we will create a UI that takes input from users. Users can interact with the UI and press Enter Key to trigger an event through this. We will be creating an input field that takes the message as input.

How do you blur input on enter?

If you want to fire blur event with key enter event, then simply pass $event in function and $event. target. blur(); in the function.


2 Answers

Instead of onKeyPress, use onKeyDown which detects keyCode events.

<input type="text"
    style={{marginTop:'20%', marginLeft:'40%'}} 
    value={value} 
    onFocus={onFocus} 
    onChange={e => setValue(e.target.value)}
    onKeyDown={(e) => this.handleKeyPress(event)}
/>

And the function will be like,

handleKeyPress(e){
   if(e.keyCode === 13){
     e.target.blur(); 
     //Write you validation logic here
   }
}
like image 183
ravibagul91 Avatar answered Sep 25 '22 08:09

ravibagul91


Use refs and this.inputRef.current.blur().This is working solution.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
    this.state = {
      value: ""
    };
  }
  keypressHandler = event => {
    if (event.key === "Enter") {
      this.setState({ value: this.inputRef.current.value });
      this.inputRef.current.blur();
      this.inputRef.current.value = "";
    }
  };
  render() {
    return (
      <div>
      <label>Enter Text</label>
        <input
          type="text"
          ref={this.inputRef}
          onKeyPress={event => this.keypressHandler(event)}
        />
        <p>{this.state.value}</p>
      </div>
    );
  }
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root' />
like image 29
Avinash Avatar answered Sep 22 '22 08:09

Avinash