Update values in input onkeypress in ReactJS - javascript

I have been trying to get how to update an input based on keypress in window with ReactJS. I'm building a basic calculator, and it has only one input. I want the input to always be targeted once a key is pressed and also update the values. I also have another function for validation, so the keypress function will still pass through the validation function. Thank you!
I have something like this:
window.onkeypress = function(e){
this.inputFocus(); //my custom function to position the cursor in the input
this.setState({display: this.state.display + e.key});
}
I just don't know the proper location to fit it in cos it says syntax error: unexpected token, pointing at the "." between "window" and "onkeypress"

If you have focus on the input field, by pressing a button, it should enter the value into that input field, and so all you should need to do is make your input a controlled component by doing the following
export default class YourClass extends Component {
constructor(props) {
super(props);
this.state = {
numberValue: 0
}
}
updateValue = (numberValue) => {
this.setState({numberValue})
}
render() {
return (
<input
type='number'
value={this.state.numberValue} // this is initialized in this.state inside the constructor
onChange={(input) => this.updateValue(input.target.value)}
/>
)
}
}
So whenever you change the value, it will automatically update the state, which then sets the value of your input. This is all predicated on you having focus on that input though, so make sure it has focus.
You can assign focus by referencing the element through javascript like...
document.getElementById('yourElement').focus()

OK here it is... I called the window.onkeydown function outside the class as it doesn't update any state. And I later realised that window.onkeydown targets and add the values in the input
import ... from ...;
window.onkeydown = function(e) {
input.focus()
}
class App extends ... {
...
}
export default App;

Related

In Javascript, how can I check that DOM elements input has changed without hardcoding and comparing values?

I have the following StimulusJS controller that aims to track certain required elements (flatckpickr date selectors).
Once all those date pickers' dates have been selected, I have to enable the submit button in a form.
I'm having problems tracking that all the required inputs have been inputed by the user and since this should be a reutilizable controller, I can't hardcode a value and compare against it.
What would be an effective way to check that all requiredTargets have received input from the user?
import { Controller } from 'stimulus';
export default class extends Controller {
static targets = ["required", "deactivable"];
toggle(){
this.deactivableTargets.toggleAttribute("disabled");
}
connect() {
this.requiredTargets.forEach((element) => {
element.addEventListener('input', (event) => {
console.log(`${element} changed`);
//if (this.requiredTargets.inputed?) {
toggle();
}
})
})
}
}
Technically inputs fields will have a value of an empty string ("") by default
You can use the JavaScript Array.every method to check that all required fields have been filled and are not equal to an empty string.
This will return true or false, and depending on what the case is, you can call the toggle() method
My Approach
On each flatpickr HTML input element, connect a Stimulus action method that fires on input event.
Let's call it handleInput in this case, so our HTML should look like this
<input
data-<controller-name>-target="required"
data-action="<controller-name>#handleInput"
type="text"
placeholder="Select Date.."
data-input
>
<!-- replace <controller-name> with the actual stimulus controller name -->
Next, define the handleInput method in your controller like this
handleInput() {
const isRequiredFilled = this.requiredTargets.every(el => el.value !== '');
if (isRequiredFilled) {
this.toggle();
}
}
NB: input element has a default input event so you don't have to handle that yourself. See the documentation

Focusing input field with Mousetrap.js - but input field also pastes the hotkey as value?

Have a look at the following example. I have enhanced the official example here with some Mousetrap functionality. So whenever somebody presses alt+1, the first input field will focus, whenever somebody presses alt+2 the second input field will be focused. It works.
Problem:
However, the input field then also takes the value of whatever was pressed as the hotkey (alt+1 then renders to ¡, alt+2 renders to € in the input). But I just want this to be a hotkey, I don't want it's actual value in the input field. How do I do this?
I could clear / delete the input field completely. This would work in the example here, but I don't want to do it since in my final app the state of the input field will need to be preserved, so I cannot just delete it.
Any advice?
import React from "react"
import Mousetrap from "mousetrap"
export default class CustomTextInput extends React.Component {
constructor(props) {
super(props)
// create a ref to store the textInput DOM element
this.textInput = React.createRef()
this.textInput2 = React.createRef()
this.focusTextInput = this.focusTextInput.bind(this)
}
componentDidMount() {
Mousetrap.bind("alt+1", () => {
this.focusTextInput(1)
})
Mousetrap.bind("alt+2", () => {
this.focusTextInput(2)
})
}
focusTextInput(id) {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
if (id === 1) {
this.textInput.current.focus()
}
if (id === 2) {
this.textInput2.current.focus()
}
}
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<input type="text" ref={this.textInput} className="mousetrap" />
<input type="text" ref={this.textInput2} className="mousetrap" />
</div>
)
}
}
I
have you tried event.preventDefault() ?
Mousetrap.bind("alt+1", (e) => {
e.preventDefault();
this.focusTextInput(1);
})
Mousetrap.bind("alt+2", () => {
e.preventDefault();
this.focusTextInput(2)
})
#Dhananjai Pai solution didn't worked for me in the same case.
I know this is very old question, so I will just leave the solution, that worked for me, just if someone needs it.
<input
type="text"
placeholder="Put focus here"
name="something"
id="order-code"
class="form-control barcodeScanner"
>
if (typeof Mousetrap !== 'undefined') {
Mousetrap.bind(['`', '('], function (e) {
e.preventDefault();
$('.barcodeScanner').focus()
}, 'keyup');
}
Adding as third option the 'keyup' event solved the issue with typing inside the input.
Source:
https://craig.is/killing/mice#api.bind
There is a third argument you can use to specify the type of event to listen for. It can be keypress, keydown or keyup.
It is recommended that you leave this argument out if you are unsure. Mousetrap will look at the keys you are binding and determine whether it should default to keypress or keydown.

Trigger the keyboard event (enter key) in angular4

In my application I have a global search field which is used to filter the data in the list , list will have multiple column. From other component setting the filter value (setting to input value) it's happening but I have to trigger the manual keyboard event (enter key) action on the input.
I tried with viewChild decorator.
component.html
<input #gb type="text" placeholder="Global search.." class="changeListComponent_inputSearch" [(ngModel)]="jiraRef" />
component.ts
#ViewChild('gb') gb:ElementRef;
this.jiraRef = jiraRef;
const event = new KeyboardEvent("keypress",{ "which ": "13"});
this.gb.nativeElement.focus();
this.gb.nativeElement.dispatchEvent(event);
using this I could set the value and make a focus but keyboard event is not triggering.
Triggered the key up event using the native js code.
Placed the id attribute to the input element along with element reference.
Created the new function from inside my component.
triggerEvent(el, type) {
if ('createEvent' in document) {
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
var e = document.createEventObject();
e.eventType = type;
el.fireEvent('on'+e.eventType, e);
}
}
var el=document.getElementById('gb-search');
this.triggerEvent(el,'keyup');
I'm not sure why you are making it complicated. why not just add a keypress event to the input field, and then also be able trigger that event through a viewChild?
<input id="text1" type=text (keyup)="enterPressed()">
and then also be able to access this same method through a view child:
this.viewChild.enterPressed();
In general your inputs can be like:
<input (keydown.enter)="doEnter()">
From other component simply call to the function doEnter. How?
If the search component is in the parent it's easy because you can use ViewChild
<search-component></search-component>
#ViewChild(SearchComponent) searchComponent
..whe we need..
this.searchComponent.doEnter()
Else, typical use a Subject to subscribe. You has a service,
#Injectable({
providedIn: 'root',
})
export class KeyBoardService {
keyboard:Subject<any>=new Subject<any>()
constructor() { }
}
In your component Search, inject the service in constructor and in ngOnInit
constructor(private keyboardService:KeyBoardService){}
ngOnInit(){
this.keyboardService.keyboard.subscribe(_=>{
this.doEnter()
})
}
And in the other component
constructor(private keyboardService:KeyBoardService){}
..in anywhere..
this.keyboardService.next(null);
Exist another option that is when the two components are at time in the screen -and in the same <router-outlet></router-outlet> that is use a template reference variable and a Input. So we has
<search-component #search></search-component>
<other-component [search]=search><other-component>
in other component
#Input('search') searchComponent
..in anywhere
this.searchComponent.doEnter
You can simply use
<input type=text (keypress)="eventHandler($event)">
eventHandler(event) {
console.log(event, event.keyCode, event.keyIdentifier);
}
Solution is based on this answer
Get which key pressed from (keypress) angular2

onClick function is running on another event listener

Have been playing around with react. Have two event listeners the input which listens onChange and the button which should push the value to the array when its clicked.
Here's the code:
import React, { Component } from 'react';
let arr = [];
class App extends Component {
constructor() {
super();
this.state = {text: 'default'}
}
update( e ) {
this.setState({text: e.target.value})
}
add ( value ) {
arr.push(value)
console.log(arr)
}
render() {
return (
<div>
<h1>{this.state.text}</h1>
<input onChange={this.update.bind(this)}/>
<button onClick={this.add(this.state.text)}>Save</button>
</div>
)
}
}
export default App
The problem that the add function is running on change. Can't really get why.
Any suggestions?
onChange() triggers update()
update() calls this.setState() which changes state.
A state change causes render() to be invoked to re-render according to new state.
Rendering <button onClick={this.add(this.state.text)}>Save</button> invokes add() every time render() runs.
In order to defer invoking add(), you can define a function which gets triggered by the click event, as was shown in another answer. Alternatively, you can achieve the same functionality by adding a class method which encapsulates the trigger functionality:
addText() {
this.add(this.state.text)
}
render() {
…
<button onClick={this.addText.bind(this)}>Save</button>
This may or may not work for you, but in the context of the example, given, this would work.
Change <button onClick={this.add(this.state.text)}>Save</button>
To <button onClick={() => this.add(this.state.text)}>Save</button>
In your variant function add firing when component is rendering, and when you call setState with onChange of input you call this re-render.
The problem is add(this.state.text) is called whenever render() is called. To avoid this, you do not need to send the state as parameter, all you need to do is
<button onClick={this.add}>Save</button
or if you want to send a parameter you should bind it
<button onClick={this.add.bind(this, this.state.text)}>Save</button>

Subclass component to override event handler?

I have a complex React component (Combobox from react-widgets), and would like to change a small part of it's behavior - I want to override the onKeyDown event. If enter is pressed, I want to handle it myself, and the Combobox shouldn't see the keypress. Apart from that, I'd like it to be a drop-in replacement.
I know React strongly recommends composition over inheritance, but in this case composing seems bad - if I make a new component that includes Combobox, I'd have to forward every prop to the combobox:
class MyCombobox extends Component {
render() {
return (<Combobox data={this.props.data}
value={this.props.value}
onChanged={this.props.onChanged}
...
/>);
}
}
I also tried just including a regular Combobox, and setting onKeyDown in its container, but that didn't override the event - the original Combobox still gets the event, and my Container gets it, too:
// in MyContainer.render:
return (
<div className="MyContainer">
<Combobox data={...} onKeyDown={this.handleKeyDown} />
</div>
);
This here almost works:
class MyCombobox extends Combobox {
handleKeyDown(event) {
console.log('MyCombobox.handleKeyDown', event);
console.log(this); // this: null!
if (event.key === 'Enter') {
event.preventDefault();
// super.close(); // fails
}
}
render() {
let result = super.render();
return React.cloneElement(result, {onKeyDown: this.handleKeyDown});
}
}
I can intercept the event and prevent the Combobox from processing it. However, this is null. If I make handleKeyPress an arrow function instead, I can access this (it is the MyCombobox object), but I can't access any of the Combobox's properties. Especially super.close() doesn't work (I get "'super' outside of function or class").
I'm not sure if it helps, but you can easily pass all the props to other component this way (using ES6 unwrapping):
class SomeComponent extends React.Component {
render() {
return(
<SomeOtherComponent {...this.props} />
)
}
}
I think it might help you to solve your problem using composition.
So, this kind of works, and it seems to be doing things The React Way (composition, only passing information to children via props).
What it does is, when I enter custom text and press enter, it takes that text and closes the menu, instead of discarding the text and selecting some element of the list.
It still doesn't behave 100% like a native combo box, so I'm giving up for now and trying a different component :-). But maybe this is a useful workaround for someone else trying to "subclass" a component.
You might be able to simplify this, I'm not sure the manual handling of value is neccessary.
class MyCombobox extends Component {
handleKeyDown = (event) => {
if (event.key === 'Enter') {
event.preventDefault();
this.setState({open: false, value: event.target.value});
}
}
constructor() {
super();
this.state = {open: false, value: null};
}
render() {
return (
<Combobox value={this.state.value} open={this.state.open}
onToggle={(isOpen)=>this.setState({open:isOpen})}
onChange={(newValue)=>this.setState({value:newValue})}
onKeyDown={this.handleKeyDown} {...this.props} />
);
}
}

Categories