Here is my form and the onClick method. I would like to execute this method when the Enter button of keyboard is pressed. How ?
N.B: No jquery is appreciated.
comment: function (e) {
e.preventDefault();
this.props.comment({
comment: this.refs.text.getDOMNode().value,
userPostId:this.refs.userPostId.getDOMNode().value,
})
},
<form className="commentForm">
<textarea rows="2" cols="110" placeholder="****Comment Here****" ref="text" /><br />
<input type="text" placeholder="userPostId" ref="userPostId" /> <br />
<button type="button" className="btn btn-success" onClick={this.comment}>Comment</button>
</form>
Change <button type="button" to <button type="submit". Remove the onClick. Instead do <form className="commentForm" onSubmit={onFormSubmit}>. This should catch clicking the button and pressing the return key.
const onFormSubmit = e => {
e.preventDefault();
// send state to server with e.g. `window.fetch`
}
...
<form onSubmit={onFormSubmit}>
...
<button type="submit">Submit</button>
</form>
It's been quite a few years since this question was last answered.
React introduced "Hooks" back in 2017, and "keyCode" has been deprecated.
Now we can write this:
useEffect(() => {
const listener = event => {
if (event.code === "Enter" || event.code === "NumpadEnter") {
console.log("Enter key was pressed. Run your function.");
event.preventDefault();
// callMyFunction();
}
};
document.addEventListener("keydown", listener);
return () => {
document.removeEventListener("keydown", listener);
};
}, []);
This registers a listener on the keydown event, when the component is loaded for the first time. It removes the event listener when the component is destroyed.
Use keydown event to do it:
input: HTMLDivElement | null = null;
onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {
// 'keypress' event misbehaves on mobile so we track 'Enter' key via 'keydown' event
if (event.key === 'Enter') {
event.preventDefault();
event.stopPropagation();
this.onSubmit();
}
}
onSubmit = (): void => {
if (input.textContent) {
this.props.onSubmit(input.textContent);
input.focus();
input.textContent = '';
}
}
render() {
return (
<form className="commentForm">
<input
className="comment-input"
aria-multiline="true"
role="textbox"
contentEditable={true}
onKeyDown={this.onKeyDown}
ref={node => this.input = node}
/>
<button type="button" className="btn btn-success" onClick={this.onSubmit}>Comment</button>
</form>
);
}
this is how you do it if you want to listen for the "Enter" key.
There is an onKeydown prop that you can use and you can read about it in react doc
and here is a codeSandbox
const App = () => {
const something=(event)=> {
if (event.keyCode === 13) {
console.log('enter')
}
}
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<input type='text' onKeyDown={(e) => something(e) }/>
</div>
);
}
import React, { useEffect, useRef } from 'react';
function Example() {
let inp = useRef();
useEffect(() => {
if (!inp && !inp.current) return;
inp.current.focus();
return () => inp = null;
});
const handleSubmit = () => {
//...
}
return (
<form
onSubmit={e => {
e.preventDefault();
handleSubmit(e);
}}
>
<input
name="fakename"
defaultValue="...."
ref={inp}
type="radio"
style={{
position: "absolute",
opacity: 0
}}
/>
<button type="submit">
submit
</button>
</form>
)
}
Enter code here sometimes in popups it would not work to binding just a form and passing the onSubmit to the form because form may not have any input.
In this case if you bind the event to the document by doing document.addEventListener it will cause problem in another parts of the application.
For solving this issue we should wrap a form and should put a input with what is hidden by css, then you focus on that input by ref it will be work correctly.
If you don't have the form inside <form>, you could use this in componentDidMount():
componentDidMount = () => {
document.addEventListener("keydown", (e) =>
e.code === "Enter" && console.log("my function"))
}
componentDidMount() //<-- remove this, it's just for testing here
useEffect(() => {
const keyEnter = event => {
if (event.key === 'Enter') {
event.preventDefault()
}
}
document.addEventListener('keydown', keyEnter)
return () => {
document.removeEventListener('keydown', keyEnter)
}
}, [])
I've built up on #user1032613's answer and on this answer and created a "on press enter click element with querystring" hook. enjoy!
const { useEffect } = require("react");
const useEnterKeyListener = ({ querySelectorToExecuteClick }) => {
useEffect(() => {
//https://stackoverflow.com/a/59147255/828184
const listener = (event) => {
if (event.code === "Enter" || event.code === "NumpadEnter") {
handlePressEnter();
}
};
document.addEventListener("keydown", listener);
return () => {
document.removeEventListener("keydown", listener);
};
}, []);
const handlePressEnter = () => {
//https://stackoverflow.com/a/54316368/828184
const mouseClickEvents = ["mousedown", "click", "mouseup"];
function simulateMouseClick(element) {
mouseClickEvents.forEach((mouseEventType) =>
element.dispatchEvent(
new MouseEvent(mouseEventType, {
view: window,
bubbles: true,
cancelable: true,
buttons: 1,
})
)
);
}
var element = document.querySelector(querySelectorToExecuteClick);
simulateMouseClick(element);
};
};
export default useEnterKeyListener;
This is how you use it:
useEnterKeyListener({
querySelectorToExecuteClick: "#submitButton",
});
https://codesandbox.io/s/useenterkeylistener-fxyvl?file=/src/App.js:399-407
I have found this to be easier.
Listen for the keyDown event on the input you want to submit by pressing 'Enter" key and handle the submit action with conditional ternary operator as show below in a single line.
This is mostly used on subscribing a newsletter where there's no need of a button to submit.
Hope it helps.
<input
type="email"
placeholder="Email"
onKeyDown={e => e.key === 'Enter' ? handleSubmit : ''} />
You can use <button type='submit'></button> with nothing in the middle.
here is very optimised code
useEffect(() => {
document
.getElementById("Your-element-id")
.addEventListener("keydown", function (event) {
if (event.code === "Enter" || event.code === "NumpadEnter") {
event.preventDefault();
document.getElementById("submit-element").click();
}
});
}, []);
use mousetrap
https://www.npmjs.com/package/mousetrap
https://www.npmjs.com/package/#types/mousetrap
(yeah, I know, unfortunatelly when You use typescript u have to install types aside from basic module)
import {bind} from 'mousetrap';
const handleSubmit = async () => {
// submit func here
};
bind(['enter', 'return'], handleSubmit);
other example of using mousetrap, maybe for other purpose:
bind(['command+k', 'ctrl+k'], function(e) {
highlight([11, 12, 13, 14]);
return false;
});
So, I was looking for some solution around the same scenario where on the login page, after a user hits(press) enter button from keyboard should trigger login process.
You can configure the textbox with one of code,
<input
// rest your code
onKeyPress={ onkeyup }
/>
Please keep in mind I am using react hooks to achieve it, apart from that this link will help you understand more enter key event handler
Try this enter code here:
const enterKye=()=>{
if(e.key==="Enter"){
alert("hello");
}
}
<input type="text" onKeyPress={enterKye}>
You may approach this problem like this.
onKeyPress={e => e.key === 'Enter' && handleFormSubmit}
You can change only button type => button to submit
<form
onSubmit={e => {
e.preventDefault();
handleSubmit(e);
}}
>
<input
name="developers"
defaultValue="submit"
ref={dev}
type="radio"
/>
<button type="submit">
submit
</button>
</form>
for example next React+TS code(add use hooks for state and etc):
type Props = {
...any properties
} & [any other type if need]
//I want notice that input data type of component maybe difference from type of props
const ExampleComponent: React.FC<Props> = (props: [Props or any other type]){
const anySerice = new AnyService();
const handleSubmit = async (eventForm) => {
await anySerice.signUp();
}
const onKeyUp = (event: KeyboardEvent) => {
//you can stay first condition only
if (event.key === 'Enter' || event.charCode === 13) {
handleSubmit(event)
}
}
...other code
return (<Form noValidate validated={validated} className="modal-form-uthorize" onKeyPress={onKeyUp}>
...other components form
</Form>)
}
export default ExampleComponent;
I solved this problem by sent autoFocus property in button
<button autoFocus={true}></button>
Related
I Am failing to get the radio button selected when I press the Enter key
I tried this code here :
import { useState, useEffect } from 'react';
const HandleKeypress = () =\> {
const [itWorks, setItWorks] = useState(true)
useEffect(() => {
document.addEventListener('keypress', (e) => {
if (e.code === 'Enter') setItWorks(!itWorks)
e.preventDefault();
})
}, [])
return (
<div>
<p>{itWorks ? 'It works!' : 'It does not'}</p>
<button onClick={() => setItWorks(!itWorks)} >Press me</button>
<input type='radio' aria-selected onKeyPress={() => this.HandleKeypress } />
</div>
)
}
export default HandleKeypress;
You dont have to use onKeyPress() use onClick() instead.
You are using functional component, so, do
<input type='radio' aria-selected onClick={handleClick} />
You cant call the main component which you are working on.
So, the solution for this is
import { useState, useEffect } from 'react';
const HandleKeypress = () => {
const [itWorks, setItWorks] = useState(false)
function handleClick(){
SetItWorks(true)
}
return (
<div>
<p>{itWorks ? 'It works!' : 'It does not'}</p>
<button onClick={() =>
setItWorks(!itWorks)} >Press me</button>
<input type='radio' aria-selected onClick={handleClick} />
</div>
)
}
export default HandleKeypress;
This will work.
I want to disable the submit button on the form if the user enters a value that already exists in the task list.
'Todos' is the array that stores the list and I used 'some' to check if the input value is equal to some title. However, it doesn't work.
CODE
const [disable, setDisable] = useState(false);
const onFormSubimit = (event) => {
event.preventDefault();
if (!editTodo) { //mudar depois a condição
setTodos([...todos, {
id: uuidv4(),
title: input,
completed: false
}]);
setInput("");
} else {
updateTodo(input, editTodo.id, editTodo.completed);
}
}
const handleInputChange = (event) => {
let inputValue = event.target.value;
setInput(inputValue);
getInputValue(inputValue);
}
const getInputValue = (inputValue) => {
let some = todos.some(item => item.title === inputValue);
if (some!=disable) {
setDisable(true);
}
}
return (
<form onSubmit={onFormSubimit}>
<input type='text' name='text' placeholder='Insira o nome da tarefa' className='task-input' value={input} onChange={handleInputChange} required></input>
<button type='submit' className='button-add' disabled={getInputValue} >{editTodo ? 'Alterar' : 'Adicionar'}</button>
</form>
);
}
Your button state is dependent on input (the variable set by setInput) and todos. So the best way to handle this is via an useEffect with a dependency array.
useEffect(() => {
// Array.some returns a boolean
setDisable(todos.some(item => item.title === input))
}, [todos, input]);
Your button code
<button type='submit' className='button-add' disabled={disable} >{editTodo ? 'Alterar' : 'Adicionar'}</button>
You can also directly use this logic in button like below. In this case there is no need of useEffect
<button type='submit' className='button-add' disabled={todos.some(item => item.title === input)} >{editTodo ? 'Alterar' : 'Adicionar'}</button>
First, change your button with the code below (as it should be disabled ={disable}, not disabled={getInputValue}). And getInputValue as following.
<button type='submit' className='button-add' disabled={disable} >{editTodo ? 'Alterar' : 'Adicionar'}</button>
const getInputValue = (inputValue) => {
if (todos.some((item) => item.title === inputValue)) {
setDisable(true);
} else {
setDisable(false);
}
};
What I am trying to do: I want to make it so that when you click on a button with the mouse or with enter from the keyboard that you cannot click on it again afterwards. In other words, disable it after pressing the button one time.
Clicking for the second time with the mouse worked, but I can't get it to work with enter.
My code is as follows.
function HomeFood() {
const [food, setFood] = useState(null);
const [calories, setCalories] = useState('');
const [disabled, setDisabled] = useState(false);
async function foodData() {
const result = await axios.get(`link`);
console.log('DATA RESULTS:', result.data);
setFood(result.data)
}
function handleChange(e) {
setCalories(e.target.value);
}
function handleKeyPress(e) {
if (e.key === 'Enter') {
foodData()
}
}
return (
<div className="container">
<section className='food'>
<input
type='number'
onChange={handleChange}
onKeyPress={handleKeyPress}
/>
<button
onClick={() => {
foodData();
setDisabled(true);
}}
disabled={disabled}
>
Click here
</button>
</section>
{food && <FoodNutrients mealsData={food}/>}
</div>
);
}
I tried to use the disabled state in the onKeyPress function, but only get errors. I also tried putting it in the input of the onKeyPress, but again more errors.
Just like the onClick, invoke setDisabled in handleKeyPress:
function handleKeyPress(e) {
if (e.key === 'Enter') {
if (disabled) { // do nothing if already disabled
return;
}
foodData();
setDisabled(true);
}
}
Add a second disabled state, i.e. inputDisabled and toggle it on the same way. This allows each to disabled independently of the other.
function HomeFood() {
const [food, setFood] = useState(null);
const [calories, setCalories] = useState('');
const [disabled, setDisabled] = useState(false);
const [inputDisabled, setInputDisabled] = useState(false); // <-- new state
async function foodData() {
const result = await axios.get(`link`);
console.log('DATA RESULTS:', result.data);
setFood(result.data)
}
function handleChange(e) {
setCalories(e.target.value);
}
function handleKeyPress(e) {
if (e.key === 'Enter') {
foodData();
setInputDisabled(true); // <-- set input disabled
}
}
return (
<div className="container">
<section className='food'>
<input
type='number'
onChange={handleChange}
onKeyPress={handleKeyPress}
disabled={inputDisabled} // <-- attach disabled prop
/>
<button
onClick={() => {
foodData();
setDisabled(true);
}}
disabled={disabled}
>
Click here
</button>
</section>
{food && <FoodNutrients mealsData={food}/>}
</div>
);
}
If you wanted them to be disabled together at the same time then just use the same disabled state and setter for both.
I have a "Join" button:
const sendMessage = (e) => {
if (message) {
socket.emit('send', message, ()=>{setMessage('')});
}
}
return (
<div>
<input value={message}
onChange={(e)=>{
setMessage(e.target.value);}}
onKeyPress={(e)=>{return e.key==='Enter' ? sendMessage(e) : console.log('no good');}}
/>
</div>
)
After filling out the input field and pressing Enter, my socket-io id changes due to page refreshing. To prevent refresh, I used e.preventDefault() in sendMessage function, but despite it, the page refreshes anyway and the socket-io id changes. How to prevent page-refresh?
Your input will only cause a refresh if it's within a form which your example is not. If you need to prevent a refresh from the form you can do it within onSubmit like the following example.
import React, { useState } from "react";
export default function App() {
const [message, setMessage] = useState("");
function sendMessage(e) {
console.log(e);
}
function handleSubmit(e) {
e.preventDefault();
}
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input
value={message}
onChange={(e) => {
setMessage(e.target.value);
}}
onKeyPress={(e) => {
return e.key === "Enter" ? sendMessage(e) : console.log("no good");
}}
/>
</form>
</div>
);
}
How do I make Popconfirm perform the confirm action on [ENTER] key?
render()
{
const { deleteTask, props } = this.props
const onConfirm = (e) =>
{
deleteTask(
{
id: props._id,
})
}
return (
<Popconfirm placement="topRight" title="Delete row?" onConfirm={onConfirm} okText="Yes" cancelText="No">
<Button type="default">
Delete
</Button>
</Popconfirm>
)
}
}
If you what to perform any action using enter key word for that you need to keep the entire input fields within form and submit the form.
handleSubmit = ()=>{
// submit logic here
}
<form onSubmit={(e) => { e.preventDefault(); this.handleSubmit() }} >
// input fields here
<button type="submit" />
</form>
To check if user has clicked Enter key:-
First, <Button onClick={(event) => this.clickHandler(event)} >Click</Button>
clickHandler = (event) => {
if(event.key === 'Enter'){
// do some stuff
}
}
This code works with every library as this is vanilla javascript.