Suppressing characters in a React input
We have an input
in a React component like below:
export const InputWithNoSpaces = () => (
<label>
Enter anything but a space
<input type="text" />
</label>
);
We want to stop the user from entering spaces into the input
.
We could use the input’s pattern
attribute and validate the input’s value after the user enters it. However, we want to do something while the user is entering the value to stop a space going into the input
.
Here’s our first attempt:
export const InputWithNoSpaces = () => {
const handleKeyDown = e => {
if (e.key === " ") {
e.preventDefault();
}
};
return (
<label>
Enter anything but a space
<input
type="text"
onKeyDown={handleKeyDown}
/>
</label>
);
};
So, we handle the keydown
event and check whether the user has entered a space using event.key
. Note that event.key
is preferable to the older event.keyCode
or event.which
which have both been deprecated.
We use the event.preventDefault
to cancel the event if a space has been entered. This means the space never gets into the input’s value.
We could have used the same approach and handled the keyup
event instead of keydown
.
If we type “The cat sat on the mat” into the input
, we end up with “Thecatsatonthemat”. Nice!
What happens if we have “The cat sat on the mat” in our clipboard and paste it into the input
? Well, this will bypass the check in handleKeyDown
, meaning a space will get into our input
.
Let’s deal with this case a little later in the event pipeline using the change
event.
export const InputWithNoSpaces = () => {
...
const handleChange = e => { if (e.currentTarget.value.includes(" ")) { e.currentTarget.value = e.currentTarget.value.replace(/\s/g, ""); } }; return (
<label>
Enter anything but a space
<input type="text" onKeyDown={handleKeyDown} onChange={handleChange} />
</label> );
};
So, we check if the new value contains a space using the string’s includes
method. If it does contain a space, we replace all the spaces in the value using the string’s replace
method. Notice that we use a regular expression in the first parameter of replace
with the global flag so that all spaces are replaced. We then update the value with the modified value.
If we now paste “The cat sat on the mat” from the clipboard into the input
, we end up with “Thecatsatonthemat”. Neat!
We could remove the keydown
handler because the change
handler will catch the case when the user presses the space key in the input
.
Below is a link to the implementation. I’ve left both the keydown
and change
handlers in the example.
If you to learn about using TypeScript with React, you may find my course useful: