rescript-compiler icon indicating copy to clipboard operation
rescript-compiler copied to clipboard

@react.component and optional arguments with default values

Open alex35mil opened this issue 1 year ago • 1 comments

Labeled optional arguments are handled differently in general functions and functions annotated with @react.component.

Playground

let fn = (~x: option<string>=Some("foo")) =>
  switch x {
  | Some(x) => x->React.string
  | None => React.null
  }

fn(~x=Some("bar"))->Console.log
fn(~x=None)->Console.log
fn()->Console.log

module RC1 = {
  @react.component
  let make = (~x: option<string>) =>
    switch x {
    | Some(x) => x->React.string
    | None => React.null
    }
}

module RC2 = {
  @react.component
  let make = (~x: option<string>="foo" /* it should be Some("foo") */) =>
    x->React.string
}

<RC1 x={Some("bar")} />->Console.log
<RC1 x={None} />->Console.log

<RC2 x="bar" />->Console.log
<RC2 x={None} />->Console.log // ← error: impossible to explicitly pass None

alex35mil avatar Feb 20 '24 08:02 alex35mil

You can pass None explicitly by using a question mark:

<RC2 x=?{None} />->Console.log

zth avatar Feb 20 '24 11:02 zth

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

github-actions[bot] avatar Feb 15 '25 01:02 github-actions[bot]