For example, if I input 123456789
and leave focus the input will change to *****6789
I have a working example but I am unsure if this is without potential bugs. Is there a better way?
I came to this through trial and error
import { useState } from "react";
import "./styles.css";
export default function App() {
const [hovered, setHovered] = useState(false);
const [testInput, setTestInput] = useState("");
const showLastFourDigits = (value) => {
if (value.length == 9) {
const result = "*".repeat(value.length - 4) + value.slice(-4);
return result;
} else {
return value;
}
};
const onSubmit = (e) => {
e.preventDefault();
console.log(testInput);
};
return (
<form className="App">
<input
value={!hovered ? showLastFourDigits(testInput) : testInput}
onChange={(e) => setTestInput(e.target.value)}
onFocus={() => setHovered(true)}
onBlur={() => setHovered(false)}
maxLength={9}
/>
<button onClick={onSubmit}>Submit</button>
<p>testInput:{testInput}</p>
</form>
);
}
As you could see. If I hover it, it shows the full input. If I unhover it, it becomes *****6789. For reason I’m not sure why but onChange doesn’t run if I do it this way. Is this secure? I’m concerned whether if i click onsubmit it might show *****6789 instead of 123456789. Is this the recommended way to do this?
3
Answers
It sounds like you want to mask and unmask in response to two criteria: element focus and hover state… and it appears as though you already figured out the
focus
andblur
logic. Great!JS doesn’t have a "hover" event, but a close approximation can be implemented using the events
mouseenter
andmouseleave
. The logic formouseenter
andmouseleave
is similar tofocus
andblur
respectively, except that they should only operate if the element is not focused.Whether the element has focus can be determined in JS by comparing the element to
document.activeElement
. Here’s a minimal, reproducible example:This is alright as long as you aren’t using
<form onSubmit= {function}>
to process the input, in which case the masked value (*****6789) will passed as the input value.I honestly would not recommend messing with the actual value just to achieve a purely visual effect. I did this in the past and ran into several problems, that weren’t apparent at first. Some things I recall:
And there is a wonderful alternative without the trouble:
Do the switcheroo purely with CSS. Place two different elements into the DOM:
pointer-events
allows fine control over which element receives the hover events.Here is an example, just to illustrate the idea: