How to pass option to component?

reasonreact

#1

Hi all
I have the following component:

let component = ReasonReact.statelessComponent("NavItemView");


let make = (~id: string, ~text: string, active: option(string), children) => {
  ...component,
  render: (_self) => {

    let navItem = <li className="nav-item" id=id>
                    <a className="nav-link">
                      {children}
                      <span className="pl-3 nav-link-text">{ReasonReact.string(text)}</span>
                    </a>
                  </li>;

    switch active {
    | None =>
      navItem
    | Some(_css) => 
      navItem
    };
  }
};  

and tried to use as following:

<NavItemView id="navItemDashboard" text="Overview" active=None>
  ...<img src={ovLogo'} height="40" width="40"/>
</NavItemView>  

The compiler complains:

  The function applied to this argument has type
    ReasonReact.reactElement =>
    ReasonReact.componentSpec(ReasonReact.stateless, ReasonReact.stateless,
                               ReasonReact.noRetainedProps,
                               ReasonReact.noRetainedProps,
                               ReasonReact.actionless)
This argument cannot be applied with label ~active

How to pass an option type to component?

Thanks


#2

It looks like active isn’t a named argument, it should look like ~active: option(string). So:

let make = (~id: string, ~text: string, ~active: option(string), children) => {

#3

What is the advantage of the labaled argument?

Thanks


#4

Component properties in ReasonReact must be labelled arguments


#5

Can I define a optional property like ~age=??
Thanks


#6

Absolutely.

In my modal component, I use lots of optionals and defaults:

let make = (~id, ~classList="", ~visible, ~onOpen=?, ~onClose=?, ~onBlur={() => ()}, children) => {
  ...component,
  didMount: (_self) => {
    switch onOpen {
      | Some(func_) => func_();
      | None => ()
    };
  },
  retainedProps: visible,
  willReceiveProps: (self) => {
    if (self.retainedProps != visible && visible == true) {
      switch onOpen {
        | Some(func_) => func_();
        | None => ()
      }
    } else if (self.retainedProps != visible && visible == false) {
      switch onClose {
        | Some(func_) => func_();
        | None => ()
        }
    }
  },
  didUpdate: ({oldSelf, newSelf}) => {
    if (oldSelf.retainedProps == false && newSelf.retainedProps == true) {
      Utils.focus(Utils.getElementById(id)) |> ignore;
    }
  },
  render: (_self) =>
    <div className="o-modal__wrapper">
      <div className={"o-modal__backdrop " ++ isVisible(visible)}></div> 
      (ReasonReact.createDomElement(
        "div",
        ~props={
          "id": id,
          "className": "o-modal " ++ classList ++ " " ++ isVisible(visible),
          "tabIndex": 1,
          "onBlur": {() => onBlur()}
        },
        children
      ))
    </div>
};