I have the following function
function CreateTextInput({ id, placeholder, defaultValue, value }) {
return (
<input
type="text"
name={id}
placeholder={placeholder}
defaultValue={defaultValue}
value={value}
//onChange={onChange}
/>
);
}
I call it like this:
Use like this: <CreateTextInput id="fieldID1" defaultValue="fieldDefaultValue" value="fieldValue" />
But it results in the field becoming read only. as in I can select the value in the field, but cant edit it. When I don’t have the "value" parameter in there, then it’s editable.
I know I could use defaultValue instead, but was just experimenting. Just wondering if this is normal behavior?
AND, in the case of setting the value on create of the object, what’s the difference between defaultValue and value anyway?
4
Answers
You have to use
useState
.The problem is that when you edit what’s in the box the new value doesn’t replace the
value
. You need to use theonChange
handler and update thevalue
with the new value — and it needs to be observable i.e., stored instate
.You can use the attribute
readOnly
when value is not
undefined
(you can remove it or explicitly set it toundefined
), the input become controlled component (the value of it is from the value attribute)Other cases, the input use the default value attribute, and you can edit it (if there is no readOnly attribute)
Yes, this is expected behavior:
So when you provide a
value
prop, your input will reflect the value supplied in that prop, thus it becomes read-only unless you update thevalue
prop accordingly withonChange
. By doing that, you’re making your input a controlled input.If you provide a
value
then there is typically no need to provide adefaultValue
as well, as yourdefaultValue
will be overwritten by what you specify in thevalue
prop:In the example case above, it’s only if
value
becomesundefined
ornull
wheredefaultValue
kicks in.