How to trigger a button click on Enter in React
In this tutorial, we are going to learn about triggering the button click by pressing an enter key in a input
box using react.
Consider we have a search form with input
field, submit button, a user can submit the form by pressing the enter key in an input field or by clicking a submit
button.
import React, { useState } from "react";
export default function App() {
const [value, setValue] = useState("");
const handleChange = e => {
setValue(e.target.value);
};
const handleSubmit = e => {
e.preventDefault();
alert("you have searched for - " + value);
// or you can send to backend
};
return (
<div className="App">
<form>
<input value={value} onChange={handleChange}/>
<button onClick={handleSubmit} type="submit"> Submit </button> </form>
</div>
);
}
Currently, we can only submit the form by clicking a submit
button let see how can we submit the form by pressing an Enter key.
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.
import React, { useState } from "react";
export default function App() {
const [value, setValue] = useState("");
const handleChange = e => {
setValue(e.target.value);
};
const handleSubmit = e => {
e.preventDefault();
alert("you have searched for - " + value);
// or you can send data to backend
};
const handleKeypress = e => { //it triggers by pressing the enter key if (e.keyCode === 13) { handleSubmit(); } };
return (
<div className="App">
<form>
<input
value={value}
onChange={handleChange}
onKeyPress={handleKeypress} />
<button onClick={handleSubmit} type="submit">
Submit
</button>
</form>
</div>
);
}
In the above code, we are not triggering the button
click by pressing a Enter
key. Instead of that, we are calling the same method (that is handleSubmit
) when a button
is clicked.
Similarly, we can also trigger the button
click like this.
import React, { useState } from "react";
export default function App() {
const [value, setValue] = useState("");
const handleChange = e => {
setValue(e.target.value);
};
const handleSubmit = e => {
e.preventDefault();
alert("you have searched for - " + value);
// or you can send data to backend
};
const handleKeypress = e => {
if (e.keyCode === 13) {
this.btn.click(); }
};
return (
<div className="App">
<form>
<input
value={value}
onChange={handleChange}
onKeyPress={handleKeypress} />
<button
onClick={handleSubmit}
ref={node => (this.btn = node)} type="submit"
>
Submit
</button>
</form>
</div>
);
}