'How to fix chakra-ui onChange trigger issue on PinInput Component
PinInput Component's onChange event doesn't working with the value in Chakra-UI so it is triggering even tough value doesn't change and that causes to move focus automatically to the next input once.
For Example: When I try set false the state of manageFocus attribute at the onChange event, I expected don't move focus automatically to the next input once a field isn't filled but it moves focus automatically to the next input once even though the field isn't filled.
In that example try to type invalid input to the Pin Input Field (you can write 6 it will set manageFocus attribute to false) and You will see manageFocus state will have setted to false after Pin Input moves focus to the next input once.
So is there a way configure onChange event or set the manageFocus attribute before focus change.
Note: The if statement is allowing only unique numbers between 1 to 5 with Regular Expression.
"^(?:([1-5])(?!.\1))$"
You can see the code down below:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import {
HStack,
PinInput,
PinInputField,
ChakraProvider
} from "@chakra-ui/react";
function App() {
const [value, setValue] = useState("");
const [canMoveNext, setCanMoveNext] = useState(true);
const regex = new RegExp("^(?:([1-5])(?!.*\\1))*$");
const handleChange = (e) => {
if (!regex.test(e)) {
setCanMoveNext(false);
return;
}
setCanMoveNext(true);
setValue(e);
};
return (
<ChakraProvider>
<HStack>
<PinInput
type="number"
manageFocus={canMoveNext}
value={value}
onChange={handleChange}
>
<PinInputField />
<PinInputField />
<PinInputField />
<PinInputField />
<PinInputField />
</PinInput>
</HStack>
</ChakraProvider>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Also you can see live at: codesandbox
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
