ciam-six-digits-input.tsx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { forwardRef } from 'react'
  2. import { Form, FormControlProps } from 'react-bootstrap'
  3. import classnames from 'classnames'
  4. interface CIAMSixDigitsInputProps extends FormControlProps {
  5. value: string | undefined
  6. }
  7. const separator = '\u2007' // figure space
  8. const CIAMSixDigitsInput = forwardRef<
  9. HTMLInputElement,
  10. CIAMSixDigitsInputProps
  11. >(({ className, onChange, value, ...props }, ref) => {
  12. const group1 = value?.slice(0, 3) || ''
  13. const group2 = value?.slice(3, 6) || ''
  14. const displayValue = group2 ? `${group1}${separator}${group2}` : group1
  15. return (
  16. <div className="ciam-six-digits-container">
  17. <Form.Control
  18. ref={ref}
  19. {...props}
  20. size="lg"
  21. onChange={v => {
  22. const inputValue = v.target.value
  23. const sanitizedValue = inputValue.replaceAll(/\D/g, '').slice(0, 6)
  24. onChange?.({
  25. ...v,
  26. target: { ...v.target, value: sanitizedValue },
  27. currentTarget: { ...v.currentTarget, value: sanitizedValue },
  28. })
  29. }}
  30. value={displayValue}
  31. className={classnames(
  32. 'form-control-ds ciam-six-digits-input',
  33. className
  34. )}
  35. maxLength={7}
  36. inputMode="numeric"
  37. />
  38. <span className="ciam-six-digits-dash" aria-hidden>
  39. -
  40. </span>
  41. </div>
  42. )
  43. })
  44. CIAMSixDigitsInput.displayName = 'CIAMSixDigitsInput'
  45. export default CIAMSixDigitsInput