16

How to use onChange in Solid.js

 2 years ago
source link: https://typeofnan.dev/how-to-use-onchange-in-solidjs/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

TypeOfNaN

How to use onChange in Solid.js

Nick Scialli • February 22, 2022 • 🚀 1 minute read

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:

onchange

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:

oninput

Did this post help you?

I'd appreciate your feedback so I can make my blog posts more helpful. Did this post help you learn something or fix an issue you were having?


If you'd like to support this blog by buying me a coffee I'd really appreciate it!


Subscribe to my newsletter

Join 1,575+ other developers and get free, weekly updates and code insights directly to your inbox.

  • No spam
  • Unsubscribe whenever
Email Address

Powered by Buttondown

Nick Scialli

Nick Scialli is a software engineer at the U.S. Digital Service.

© 2022, Built using Gatsby

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK