S
SolidJS13mo ago
snorbi

Handling <input>

Is this a correct way to handle <input> fields? <input onInput={e => setUserName(e.target.value)} value={userName()} /> Or should I use a ref instead and read the field value when it is needed? Is there a concept of "controlled input" in solidjs? Or only "uncontrolled input"? Thanks.
4 Replies
Madaxen86
Madaxen8613mo ago
Yes it is the correct way for a controlled input. And you can alternatively use uncontrolled inputs. Both concepts exist.
juanrgm
juanrgm13mo ago
Really this is not controlled input, it's pseudo controlled input If you drop the onInput attribute, the value is not frozen
Madaxen86
Madaxen8613mo ago
Well not a controlled by React’s definition. Because in Solid all elements are real HTML elements they will fallback to their native behavior. For an input value is then just the defaultValue in Reacts sense. But you can control what's displayed on the input e.g. make all characters lowercase. That's controlled for me...
const [email, setEmail] = createSignal("");
const val = () => email().toLowerCase();

return (
<>
<label>Email</label>
<input
onInput={e => setEmail(e.target.value)}
value={val()} />
</>
);
const [email, setEmail] = createSignal("");
const val = () => email().toLowerCase();

return (
<>
<label>Email</label>
<input
onInput={e => setEmail(e.target.value)}
value={val()} />
</>
);
snorbi
snorbiOP13mo ago
Thanks!

Did you find this page helpful?