How to use onChange in Solid.js
Nick Scialli
February 22, 2022
New — Check out my free newsletter on how the web works!
If you’re used to React, you might be wondering why the Solid onChange handler doesn’t work how you’d expect.
The problem
You may be writing a Solid component with the following code:
function App() {
const [text, setText] = createSignal('');
return (
<>
<input
onChange={(e) => {
setText(e.target.value);
}}
/>
<div>
<strong>Your text is:</strong> {text}
</div>
</>
);
}
But you’ll quickly notice things aren’t working as you might expect:
The text
isn’t reflected in the div
like we would hope until after we tab out of the input. This is actually intended behavior and more in line with native behavior.
From the Solid.js docs:
Note that onChange and onInput work according to their native behavior. onInput will fire immediately after the value has changed; for input fields, onChange will only fire after the field loses focus.
The solution
As described above, you’re looking for the onInput
handler, which more closely mirrors native oninput behavior:
function App() {
const [text, setText] = createSignal('');
return (
<>
<input
onInput={(e) => {
setText(e.target.value);
}}
/>
<div>
<strong>Your text is:</strong> {text}
</div>
</>
);
}
Now if we run our app, we see the text
updating immediately:
🎓 Learn how the web works
One of the best ways to level up your tech career is to have a great foundational understanding of how the web works. In my free newsletter, How the Web Works, I provide simple, bite-sized explanations for various web topics that can help you boost your knowledge. Join 2,500+ other learners on the newsletter today!
Signing up is free, I never spam, and you can unsubscribe any time. You won't regret it!
Sign up for the newsletter »Nick Scialli is a senior UI engineer at Microsoft.