card-element.tsx 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { useState, useEffect, useRef } from 'react'
  2. import { useTranslation } from 'react-i18next'
  3. import { FormGroup, ControlLabel } from 'react-bootstrap'
  4. import { CardElementChangeState } from '../../../../../../../types/recurly/elements'
  5. import { ElementsInstance } from 'recurly__recurly-js'
  6. import classnames from 'classnames'
  7. type CardElementProps = {
  8. className?: string
  9. elements: ElementsInstance
  10. onChange: (state: CardElementChangeState) => void
  11. }
  12. function CardElement({ className, elements, onChange }: CardElementProps) {
  13. const { t } = useTranslation()
  14. const [showCardElementInvalid, setShowCardElementInvalid] =
  15. useState<boolean>()
  16. const cardRef = useRef<HTMLDivElement>(null)
  17. // Card initialization
  18. useEffect(() => {
  19. if (!cardRef.current) return
  20. const card = elements.CardElement({
  21. displayIcon: true,
  22. inputType: 'mobileSelect',
  23. style: {
  24. fontColor: '#5d6879',
  25. placeholder: {},
  26. invalid: {
  27. fontColor: '#a93529',
  28. },
  29. },
  30. })
  31. card.attach(cardRef.current)
  32. card.on('change', state => {
  33. setShowCardElementInvalid(!state.focus && !state.empty && !state.valid)
  34. onChange(state)
  35. })
  36. }, [elements, onChange])
  37. return (
  38. <FormGroup
  39. className={classnames(className, { 'has-error': showCardElementInvalid })}
  40. >
  41. <ControlLabel>{t('card_details')}</ControlLabel>
  42. <div ref={cardRef} />
  43. {showCardElementInvalid && (
  44. <span className="input-feedback-message">
  45. {t('card_details_are_not_valid')}
  46. </span>
  47. )}
  48. </FormGroup>
  49. )
  50. }
  51. export default CardElement