Trigger onblur event on click of enter keypress in React js
Asked Answered
M

3

14

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}
/>
Marlie answered 20/5, 2019 at 8:36 Comment(0)
R
8

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' />
Reconcile answered 20/5, 2019 at 8:56 Comment(1)
From the docs Avoid using refs for anything that can be done declaratively. and Don’t Overuse Refs -reactjs.org/docs/refs-and-the-dom.htmlErrick
E
26

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
   }
}
Errick answered 20/5, 2019 at 8:50 Comment(3)
MDN docs say KeyboardEvent.KeyCode is deprecated. "Avoid using it, and update existing code if possible; [...] Be aware that this feature may cease to work at any time." And "You should avoid using this if possible; it's been deprecated for some time. Instead, you should use KeyboardEvent.code, if it's implemented [...] be careful to make sure you use one which is supported on all target browsers."Panatella
There is also KeyboardEvent.key which is probably a better choice for just detecting that the user has pressed Enter.Panatella
Note that this correctly triggers the blur event but it removes certain default behaviour of the input that used to be triggered by the Enter key (such as submitting a form, automatically moving to the next field in the form, etc).Anguine
R
8

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' />
Reconcile answered 20/5, 2019 at 8:56 Comment(1)
From the docs Avoid using refs for anything that can be done declaratively. and Don’t Overuse Refs -reactjs.org/docs/refs-and-the-dom.htmlErrick
L
2

One-liner would be:

<input
...
onKeyDown={(e) => e.key === "Escape" && e.target.blur()}    
/>
Linstock answered 28/8, 2023 at 16:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.