DEV Community

Cover image for use onSubmit, not onClick
Terrel Shumway
Terrel Shumway

Posted on

use onSubmit, not onClick

The SolidJS tutorial has several pages that work with a To Do list app. This is the form used:

<div>
    <input ref={input} />
    <button onClick={(e) => {
        if (!input.value.trim()) return;
        addTodo(input.value);
        input.value = "";
        }}
>Add Todo</button>
</div>
Enter fullscreen mode Exit fullscreen mode

If you are doing your own To Do list (or any app that has a form with a single input field) you should do this instead:

<form onSubmit={(e) => {
    e.preventDefault()
    if (!input.value.trim()) return;
    addTodo(input.value);
    input.value = "";
    }}>
    <input autofocus ref={input} />
    <button>Add Todo</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Putting the action in the onClick handler forces the user to click the button.
Putting the action in the onSubmit handler allows the user to just press Enter.
autofocus magically returns focus to the input, nicer than an imperative input.focus().
Also consider e.target.reset() over input.value="".

Top comments (2)

Collapse
 
xwero profile image
david duymelinck

While I agree it should be changed, The tutorial is not about the button, so it is a minor error in that context.

The bigger problem with that button for me is that it uses an anonymus function. Why not move the function outside the markup, like the addTodo and toggleTodo functions.

Collapse
 
terrelcodes profile image
Terrel Shumway

Yes, it is peripheral. Therefore, doing it right would not change what matters. I was annoyed by this in several projects inspired by this tutorial. When I finally figured out how to do it right, I documented it immediately.