0
I’m trying to catch the event onChange native of the browser, since the onChange React is executed with each key pressed by the user. It is possible to implement this?
The native event I believe occurs as follows: user pressed enter or left the current field (Blur).
The only alternative I’ve found so far is to combine the events onChange, onBlur and onKeyDown, being similar to this:
import React, { useEffect, useRef, useState } from 'react';
import { Input } from 'reactstrap';
import PropTypes from 'prop-types';
export function InputText({
value: userValue,
onChange: userOnChange,
onBlur: userOnBlur,
onKeyDown: userOnKeyDown,
...props
}) {
const [value, setValue] = useState('');
const hasChanges = useRef(false);
useEffect(() => {
setValue(userValue);
}, [userValue]);
function dispatchChange(event) {
if (hasChanges.current) {
hasChanges.current = false;
if (userOnChange) {
userOnChange(event);
}
}
}
function onChange(event) {
setValue(event.target.value);
hasChanges.current = true;
}
function onBlur(event) {
dispatchChange(event);
if (userOnBlur) {
userOnBlur(event);
}
}
function onKeyDown(event) {
if (event.keyCode === 13) {
dispatchChange(event);
}
if (userOnKeyDown) {
userOnKeyDown(event);
}
}
return (
<Input
value={value}
onChange={onChange}
onBlur={onBlur}
onKeyDown={onKeyDown}
{...props}
/>
);
}
InputText.propTypes = {
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]).isRequired,
onChange: PropTypes.func,
onBlur: PropTypes.func,
onKeyDown: PropTypes.func
};
In this way, I have a similar behavior. It seems to me "gambiarra". Is there any way to get the same behavior in a simpler way?
Use the HTML input field instead of being a component.
– Diego Souza