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}
/>
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.
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.
If you want to fire blur event with key enter event, then simply pass $event in function and $event. target. blur(); in the function.
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
}
}
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' />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With