Search code examples
javascriptreactjsinputfocus

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}
/>

Solution

  • 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' />