I have an issue where the condition that enables or disables input field through HTML attribute according to the React state only works for the first time. I don't know if this is a limit and it has to be done differently or I am missing something in a sea of unexpected behavior with JS React and state.
I have following fields isFixedAmount and fixedAmount. The first one is boolean while the second is a number.
I get them from the DB on a component mount and show them in the form. If the IsFixedAmount is false I want to disable the input field for fixedAmount.
<label>Is Fixed Amount</label>
<select
value={isFixedAmount}
onChange={(e) => setIsFixedAmount(e.target.value)}
>
<option value={true}>Yes</option>
<option value={false}>No</option>
</select>
<label>Fixed Amount</label>
<input
type="number"
name="fixedAmount"
disabled={isFixedAmount ? false : true}
value={fixedAmount}
onChange={(e) => setFixedAmount(e.target.value)}
/>
On the first render I get the correct result. I can change one time and it works, however every next change leaves the input field as with the last change.
When I inspect it through Components in ReactDevTools I see state value for isFixedAmount properly changing with each selection but the input field disabled attribute is not doing anything after the first change, it's like it is not listening to it anymore.
CodePudding user response:
The problem is that the values passed in select input are passed as strings.
You can do
onChange={() => setIsFixedAmount((previousState) => !previousState)}
CodePudding user response:
Because the select
element only accept string | number | read-only string[] type so that the isFixedAmount
became the string type when you selected.
So the input of disabled
is always false.
CodePudding user response:
i think isFixedAmount value is string so it doesn't work properly so you need to change the code on
<input
type="number"
name="fixedAmount"
disabled={isFixedAmount === 'true' ? false : true}
value={fixedAmount}
onChange={(e) => setFixedAmount(e.target.value)}
/>
for example console the value it has to be a string typeof(e.target.value)