I'm working on the validation of an AutoComplete control using React JS and MaterialUI, by default the option "please select.." is loaded like in this image:
If the user press Send Order and the selected value is the first one an error message is sent to the user; but If the user chose a different option, the state of the Autocomplete is still in error, please take a look at this picture:
The below code shows you how I'm manage the AutoComplete code:
<div className={clientMethodPaymentControlClasses}>
<label htmlFor="clientMethodPayment">Method of Payment *</label>
<Autocomplete
id="clientMethodPayment"
options={paymentMethods}
defaultValue={paymentMethods[0]}
getOptionLabel={(option) => option.title}
ref={clientMethodPaymentRef}
onChange={(e,v) => setPaymentMethodValue(v)}
style={{ width: 300 }}
autoHighlight
renderInput={(params) => (
<TextField {...params} onChange={({ target }) => setPaymentMethodValue(target.value)} variant="outlined" fullWidth autoComplete="off" />
)}
/>
{!formInputsValidity.clientMethodPayment && (
<p>Please choose a method of payment</p>
)}
</div>
I use the bellow code for list of values and how I manage the control's state:
const paymentDefaultValue = (value) => value !== "Please choose an option";
const paymentMethods = [
{ title: "Please choose an option", id: 0 },
{ title: "Cash", id: 1 },
{ title: "Credit Card", id: 2 },
{ title: "Crypto Currency", id: 3 },
];
const OrderDetails = (props) => {
const [paymentMethodValue, setPaymentMethodValue] = useState(paymentMethods[0]);
Moreover, the next code is the key to classify if a control has input errors:
const enteredClientMethodPaymentIsValid = !paymentDefaultValue(
enteredClientMethodPayment
);
The fact is that I can't catch if the user chose a different option rather than the default one and for that reason the control is always marked as error, so my question is: what am I missing to validate my AutoComplete control? In case it might be useful this is the full code: https://github.com/hftamayo/reactletsorder/blob/unstable/src/components/FoodOrder/Cart/OrderDetails.js
Thanks a lot