-1

My english is not well, I have a credit card component. when input change get value to other component. But I want expiry month and year to get from dropdown. Here is the code, can anyone help?

codesandbox.io/s/purple-frost-lknxs

paws
  • 91
  • 1
  • 10

1 Answers1

1

CreditCardForm receives an onChange callback from Payment which uses to update name, number, expiryMonth and expiryYear properties.

The problem here is that the onChange callback for expiryMonth and expiryYear is being triggered from DropdownToggle's onChange event rather than from DropdownItem -> div -> onClick event, which is the event that you're really interested in:

<Dropdown isOpen={dropdownOpen} toggle={toggle}>
  <DropdownToggle
    caret
    id="expiryMonth"
    name="expiryMonth"
    value={expiryMonth}
    onChange={(e) =>  <-- It's being called HERE
      onChange({ key: "expiryMonth", value: e.target.value })
    }
  >
    {dropDownValue}
  </DropdownToggle>
  <DropdownMenu>
    {select.map((item, index) => {
      return (
        <DropdownItem
          key={`${item.id}--${index}`}
          className={classNames({
            active: dropDownValue === item.text
          })}
        >
          <div onClick={changeValue}>{item.value}</div> <-- Should be called HERE
        </DropdownItem>
      );
    })}
  </DropdownMenu>
</Dropdown>

A simple solution is to extend both changeValue and changeValue2 to call the onChange callback with the proper keys:

function changeValue(e) {
  setDropDownValue(e.currentTarget.textContent);
  onChange({ key: "expiryMonth", e.currentTarget.textContent })
}

function changeValue2(e) {
  setDropDownValue2(e.currentTarget.textContent);
  onChange({ key: "expiryYear", e.currentTarget.textContent })
}

It's also a good idea to change the initialState in Payment component so initialState starts with the same values as the Dropdowns:

const initialState = {
  name: "",
  number: "",
  expiryMonth: "01",
  expiryYear: "01",
  cvv: ""
}
Turtlean
  • 579
  • 4
  • 9