onClick optional prop



Hey everyone, newcomer here.

I’ve been trying to create a showcase library to demonstrate reason as an option.
The problem is that I am stuck on the basics.


The question: how can I make an optional prop for my onClick? It is always dropping this kind of error. I’ve looked everywhere and didn’t found.

If my explanation lacks information, please, ask me and I will provide more :slight_smile:


Hello and welcome to the community :wave:

It should work, when you wrap it in option() like so:

let make = (~onClick: option(ReactEvent.Mouse.t => unit)) => {

Also you probably don’t have to type the onClick.
I am having the following react component (example) in one of my projects:

let make = (~target="_self", ~onClick, ~href, ~children) => {
  let handleClick = evt => {
    switch (onClick) {
    | Some(func) => func(evt)
    | None => ()

  <a href target onClick=handleClick> children </a>;

As you can see, I haven’t typed any of the pararmeters, because they are inferred by the compiler.


Thank you so much <3 Worked


There’s also the =? syntax sugar that’s handy in these cases. It says that the param is optional. ?onClick means "pass it on if it’s Some(func)".

let make = (~target="_self", ~onClick=?, ~href, ~children) => {
  <a href target ?onClick> children </a>;

or, if you want to put explicit types:

let make = (~target="_self", ~onClick: option(ReactEvent.Mouse.t => unit)=?, ~href, ~children) => {
  <a href target ?onClick> children </a>;