Reputation: 95
I have a credit card component. when user select expire month or expire year from select, I want to get value in p tag. Controller code is here, if I use render with controller its working but not giving error.
<Controller
as={<Select options={years} />}
name="expiryYear"
onChange={(inputValue) => changeValue(inputValue.value)}
control={control}
defaultValue={null}
rules={{
required: true
}}
/>
How it giving error when its null and get value in the p tag? and here is the sandbox link https://codesandbox.io/s/cool-http-rbzfp
Upvotes: 1
Views: 10041
Reputation: 19268
I think you want to use watch/usewatch to retrieve the input value:
https://react-hook-form.com/api#watch
https://react-hook-form.com/api#useController
import React, { useState } from "react";
import { useForm, Controller } from "react-hook-form";
import Select from "react-select";
const CreditCardForm = ({
cardInfo: { number, expiryMonth, expiryYear },
onChange
}) => {
const months = [
{ value: "01", label: "01" },
{ value: "02", label: "02" },
{ value: "03", label: "03" },
{ value: "04", label: "04" },
{ value: "05", label: "05" },
{ value: "06", label: "06" },
{ value: "07", label: "07" },
{ value: "08", label: "08" },
{ value: "09", label: "09" },
{ value: "10", label: "10" },
{ value: "11", label: "11" },
{ value: "12", label: "12" }
];
const years = [
{ value: "2021", label: "2021" },
{ value: "2022", label: "2022" },
{ value: "2023", label: "2023" },
{ value: "2024", label: "2024" },
{ value: "2025", label: "2025" },
{ value: "2026", label: "2026" },
{ value: "2027", label: "2027" },
{ value: "2028", label: "2028" },
{ value: "2029", label: "2029" }
];
const { register, errors, watch, formState, control } = useForm({
mode: "all",
reValidateMode: "onBlur"
});
console.log(watch());
function changeValue(inputValue) {
onChange({
key: "expiryMonth",
value: inputValue.label
});
}
function changeValue2(inputValue) {
onChange({
key: "expiryYear",
value: inputValue.label
});
}
return (
<form>
<div className="form-group expires">
<div className="expires__select">
{errors.expiryMonth && (
<span className="input__error-message">required</span>
)}
<Controller
as={<Select options={months} />}
name="expiryMonth"
// onChange={(inputValue) => changeValue(inputValue.value)}
control={control}
defaultValue={null}
rules={{
required: true
}}
/>
</div>
<div className="expires__select">
{errors.expiryYear && (
<span className="input__error-message">required</span>
)}
<Controller
as={<Select options={years} />}
name="expiryYear"
// onChange={(inputValue) => changeValue2(inputValue.value)}
control={control}
defaultValue={null}
rules={{
required: true
}}
/>
</div>
</div>
</form>
);
};
export default CreditCardForm;
Upvotes: 1