onClick optional prop

reasonreact

#1

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.

Screenshot%20from%202020-03-04%2009-57-47

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:


#2

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:

[@react.component]
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.


#3

Thank you so much <3 Worked


#4

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)".

[@react.component]
let make = (~target="_self", ~onClick=?, ~href, ~children) => {
  <a href target ?onClick> children </a>;
};

or, if you want to put explicit types:

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