I have a component with the following handler:
<MyComponent onKeyDown={handler} />
The handler looks like this:
const handler = (e: KeyboardEvent) => {
if (e.key === 'Backspace') {
const slicedString = input.slice(0, -1);
setInput(slicedString);
}
};
And this is my useState hook:
const [input, setInput] = useState<string>('');
I want to slice the last character of the input when 'Backspace'
is pressed onKeyDown
event.
The slicedString
gets updated when backspace is pressed but the input
state stays the same. I know that the spread operator has to be used for objects and arrays but how can I update the state when a string is used?