Form Submit event in rescript

I wrote this code. it prevents reloading of the page and then writes something to the log.

let onButtonClick = event => {
  ReactEvent.Form.preventDefault(event)
  Js.Console.log("Button clicked")
}

@react.component
let make = () => {
  <main>
    <form className={styles["form"]}>
      <input type_="text" placeholder="Top Text" className={styles["form--input"]}/>
      <input type_="text" placeholder="Bottom Text" className={styles["form--input"]} />
      <button 
        onClick={onButtonClick}
        className={styles["form--button"]}>
          {"Get a new Meme image" -> React.string}
      </button>
    </form>
  </main>
}

Rescript compiler is throwing a very cryptic error at me… why is bothered about the “mouse”?

This has type: ReactEvent.Form.t => unit
  Somewhere wanted: JsxEvent.Mouse.t => unit
  
  The incompatible parts:
    ReactEvent.Form.t (defined as JsxEvent.synthetic<ReactEvent.Form.tag>) vs
    JsxEvent.Mouse.t (defined as JsxEvent.synthetic<JsxEvent.Mouse.tag>)
    
    Further expanded:
      ReactEvent.Form.tag (defined as JsxEvent.Form.tag) vs
      JsxEvent.Mouse.tag

The click event will pass a “MouseEvent” - not a “FormEvent”. So instead of using ReactEvent.Form.preventDefault use ReactEvent.Mouse.preventDefault.

The title of this question is asking something different.

Your code would have worked if you’d have used the form’s onSubmit prop instead:

let onSubmit = event => {
  ReactEvent.Form.preventDefault(event)
  Js.Console.log("Form submitted ")
}

@react.component
let make = () => {
  <main>
    <form onSubmit={onSubmit}>
      <input type_="text" placeholder="Top Text" />
      <input type_="text" placeholder="Bottom Text" />
      <button type_="submit"> {"Get a new Meme image"->React.string} </button>
    </form>
  </main>
}

but it seems you were interested in defining a button click callback?

3 Likes

Thanks for the explanation now I understand what was going on. The error message said something about Mouse Event. I guess Mouse click is synonymous with button click? or can the error message be improved here?

Any click event is a MouseEvent, no matter the target, and notwithstanding the fact that with a button, it can be triggered by Enter/Space.

1 Like