'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 1:[1]
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' />
Solution 2:[2]
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
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Avinash |
Solution 2 | Patrick M |