Enter key for Route another page - javascript

I have a input for searchbox. I must make like; Write my words fors search then after i press enter it must need go another page with input value. So i can access that value with query string. So how can i route another page with value of input after i press enter ? Thank you for help! I Just add That codes for catch enter press.
useEffect(() => {
const listener = (event) => {
if (event.code === "Enter" || event.code === "NumpadEnter") {
alert("Enter key was pressed. Run your function.");
event.preventDefault();
}
};
document.addEventListener("keydown", listener);
return () => {
document.removeEventListener("keydown", listener);
};
}, []);

You don't necessarily have to set an event listener, using onKeyDown event handler will also do. Enter key has a code of 13, so we just have to detect that.
Keep your value in a state (here, myValue), detect that you've pressed Enter key (here, using keyPressHandler method), and finally, pass the parameter to your route.
import {useHistory} from "react-router-dom"
function App() {
let history = useHistory();
const [myValue, setMyValue] = useState("");
const handleChange = ({ target: { value } }) => {
setMyValue(value);
};
const keyPressHandler = (e) => {
if (e.which === 13) {
// alert("You pressed enter!");
history.push("/process/" + myValue);
}
};
return (
<div className="App">
<input value={myValue} onKeyDown={keyPressHandler} onChange={handleChange} />
</div>
);
}
UPDATE:
According to MDN Web Docs, e.which is non-standard [Source] and e.keyCode is deprecated [Source], so you should be using e.key instead like:
const keyPressHandler = (e) => {
if (e.key=== 'Enter') {
// alert("You pressed enter!");
history.push("/process/" + myValue);
}
};
Working CodeSandbox Link

Related

Use react to focus input element with caret/text-cursor at end of text using onKeyDown

I have two input fields in my component:
const MyComponent = () => {
const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'ArrowLeft') {
ref.current?.setSelectionRange(value.length, value.length)
ref.current?.focus()
}
}
const [value, setValue] = useState('1234')
const ref = useRef<HTMLInputElement>(null)
return (
<>
<input
onChange={({target}) => setValue(target.value)}
value={value}
ref={ref}
type={'text'}/>
<input
onKeyDown={onKeyDown}
type={'text'}/>
</>
)
}
When i hit the left arrow-key on the second input, the first input should be focused, and the cursor should be at the end of the input text.
But the cursor is at the wrong place. Why is this not working?
Was the cursor moving one position to the left of the last character?
Interestingly, when using onKeyUp (the release of the key) rather than onKeyDown the issue seems to go away. I've listed that solution followed by a couple other examples with explanations below.
Solution
import { useRef, useState } from "react";
const MyComponent = () => {
const [value, setValue] = useState("1234");
const ref = useRef(null);
const onKeyUp = (event) => {
if (event.key === "ArrowLeft") {
const textInput = ref.current;
const len = value.length;
textInput.setSelectionRange(len, len);
textInput.focus();
}
};
return (
<>
<input
onChange={({ target }) => setValue(target.value)}
value={value}
ref={ref}
type={"text"}
/>
<input onKeyUp={onKeyUp} type={"text"} />
</>
);
};
export default MyComponent;
https://codesandbox.io/s/cursor-end-of-input-onkeyup-x6ekke
Explanation
My guess is that because onKeyUp naturally follows onKeyDown, when we receive the onKeyDown event in React, per your example code, the following sequence occurs (or generally speaking something like this is happening):
Inside onKeyDown...
Our cursor is moved to the very end of the text input.
ref.current?.setSelectionRange(value.length, value.length)
The text input receives focus.
ref.current?.focus()
Then, the release of the left arrow key causes onKeyUp event to run in the DOM (we haven't done anything to handle this in React) while the focus is now on the text input as a result of step 2 above. The default behavior pressing/releasing the left arrow key while the input has focus is to move the cursor one position to the left, placing it one position from the end of the input text.
Other Examples/Solutions
If you stick with the use of onKeyDown, here are a couple other examples.
event.preventDefault()
const onKeyDown = (event) => {
if (event.key === "ArrowLeft") {
event.preventDefault();
const textInput = ref.current;
const len = value.length;
textInput.setSelectionRange(len, len);
textInput.focus();
}
};
setTimeout()
const onKeyDown = (event) => {
if (event.key === "ArrowLeft") {
setTimeout(() => {
const textInput = ref.current;
const len = value.length;
textInput.setSelectionRange(len, len);
textInput.focus();
}, 0);
}
};
https://codesandbox.io/s/cursor-end-of-input-example-h1yrdr
My guess is that these workarounds effectively block the browser from firing the native key down and up events altogether or delay our handler from running until after the native events have fired, respectively.

React - Can I verify if user pressed a key or not with on change event?

I need to know if I can verify if user pressed a key or not only with onchange event, because I get the text on input with a QR reader, but there also exists the possibility for the user to manually enter the data.
I have this code (example):
_getValue = (event) => {
let value = event.target.value;
}
render() {
<input type="text" onChange={this._getValue} />
}
So, on _getValue method, which is from an onchange event, I need to check if the change is coming from a key or from the QR reader.
Thank you to all!
You could use the keydown event.
You would probably end up with something like this
_getValue = (event) => {
let value = event.target.value;
}
const handleKeyPress = (e) => {
e.preventDefault();
return;
}
render() {
<input type="text" onChange={this._getValue} onKeyPress={handleKeyPress} />
}
You can read more on the event on MDN

input value not responding to "keyup" event

I am having problem with the following code. It is a simple To Do app with Javascript. Following a tutorial, followed to the t. My app isn't working the way it is supposed to. When I press the enter key the input value should be added to the list and it is not. I can't find any flaw in the code.
Also when I call the function manually addToDo("read"); it shows up alright. But the enter button is not responding. Any advice will be appreciated.
document.addEventListener("keyup", function(event) {
if (event.key === 13) {
const toDo = input.value;
if (toDo) {
addToDo(toDo);
} //end if toDo
} // end if event.key
});
It doesn't work because you're not checking for the proper key value on the keyup event:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
You can check for the 'Enter' key on the keyup event like so:
txtTodo.addEventListener('keyup', (e) => {
if (e.key === 'Enter') {
console.log(e.target.value);
}
});
A live example can be found here:
https://jsfiddle.net/dbkf53w2/
function addToDo(val) {
console.log(val);
}
document
.querySelector('#input-field')
.addEventListener('keyup', function (event) {
if (event.key === 'Enter') {
const toDo = event.target.value;
if (toDo) {
addToDo(toDo);
} //end if toDo
} // end if event.key
});
<input type="text" id="input-field">
event.key value has a string value. Try with 'Enter' rather than 13. Number is keyCode. When trying to console event.keyCode then it shows numbers.
document.addEventListener("keyup", function(event){
console.log(event.keyCode);
if(event.key=== 'Enter'){
//const toDo = input.value;
//if(toDo){
// addToDo(toDo);
console.log('Enter')
//}//end if toDo
}// end if event.key
})
<div>Push 'Enter' please</div>

On mount, check if Enter/Return key is being pressed and use that information in onBlur event

I have a button that can be highlighted with Tab, where pressing Enter when the button is highlighted creates an Input field. That input field is then focused.
The input field has a keyUp event and if the key is Enter/Return, blur the field (and save the info that was put into the field).
The issue:
Tab to select Button
Keydown Enter/Return to create Input field
Input field is now focused
Keyup Enter/Return
Input becomes blurred
What I need is to know if the enter/return key was pressed on mount and stop the Keyup event from firing if that is true.
export default function EditableLabel({
active,
value: valueProp,
variant,
...rest
}) {
const [returnPressedOnMount, setReturnPressedOnMount] = useState(false);
let isReturnPressed = false;
// Only set this listener on mount
useEffect(() => {
document.addEventListener('keypress', isReturnKey, false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
function isReturnKey(event) {
console.log(event.keyCode);
if (!returnPressedOnMount && event.keyCode === 13) {
console.log('In the return key func');
setReturnPressedOnMount(true);
isReturnPressed=true;
console.log(isReturnPressed)
}
document.removeEventListener('keypress', isReturnKey, false);
}
function handleBlur(evt) {
setIsEditing(false);
rest.onChange && rest.onChange({ target: { value } });
rest.onBlur && rest.onBlur(evt);
}
function handleKeyUp(evt) {
console.log(returnPressedOnMount);
console.log(isReturnPressed);
if (evt.key === 'Enter') {
if (!returnPressedOnMount) {
const target = evt.target;
setTimeout(() => target.blur(), 0);
} else {
setReturnPressedOnMount(false);
}
}
rest.onKeyUp && rest.onKeyUp(evt);
}
return (
<Input .../>
);
}
This code works if I hold the Enter/Return key down for a long time, but if someone presses the key normally (just tap the key, not holding it down) the State/Variable do not update in time for the onKeyUp.
How do I get the knowledge of the Return key being pressed on Mount to the onKeyUp function?

How do I reset an input field on 'Enter' keyUp in React?

I am creating an input that adds to a list of tags rendered below the input. I would like the input to push the tag to the list when 'Enter' is pushed while the user is focused on the input field. The field then resets to blank or "", and the user can add another tag in the same fashion.
The problem I am having is that after the value gets reset to a blank string, any time I try to grab the value of the input an empty string is returned.
Here is what I have so far:
const [listOfOptions, addOption] = React.useState([])
let newOption = () =>{
let addField = document.getElementById('addOption')
let grabText = addField.value;
console.log('Grabtext ='+ grabText)
addOption([...listOfOptions, grabText])
addField.reset();
}
useEffect(() => {
document.getElementById('addOption').addEventListener("keyup", function(event) {
if (event.key === "Enter") {
newOption()
}}
); }, [listOfOptions])
I would avoid directly manipulating the DOM in React. Let React's Virtual DOM handle that.
You can store the value of the form in state and then on submit it resets the state to ''.
Something like this:
const [value, setValue] = useState('');
const handleFormValueChange = (event) => setValue(event.target.value);
const resetFormValue = () => setValue('');
<input type="text" value={value} onChange={(event) => handleFormValueChange(event)} />
<input type="submit" onSubmit={resetFormValue} />
The answer, taking into consideration the earlier suggestions, thanks for the help, would then be the below:
const [value, setValue] = useState('');
const [listOfOptions, addOption] = React.useState([])
const handleFormValueChange = (event) => setValue(event.target.value);
let newOption = (event) => {
if (event.key === "Enter") {
addOption([...listOfOptions, value]);
setValue('');
}
}
<input value={value} onChange={(event) => handleFormValueChange(event)} onKeyUp={(event)=>newOption(event)} id="addOption" />
This solution uses the Enter keydown to submit and reset the value, whilst modifying only React's virtual DOM.
Assuming that addOption is an <input>, <select>, or <textarea>, it should not have reset() method. Modify .value instead
addField.value = "";
Don't forget to detach eventListener on this component dismount.
useEffect(() => {
const element = document.getElementById("addOption");
const listener = event => {
if (event.key === "Enter") {
newOption();
event.preventDefault();
}
};
element.addEventListener("keyup", listener);
return () => element.removeEventListener("keyup", listener);
}, [listOfOptions]);
Also please avoid directly modifying DOM directly to a React rendered element, as it may disrupt React render process.
Instead, use a state library such as this or event library
Edit:
You should avoid manipulating DOM directly as told in this answer by David Caldwell

Categories