How to import a JS React component with invalid (keyword) prop names?

I have a React component <Switch type="switch" /> (or type="checkbox") from JS that takes a type argument. Can I import it to ReScript with @module external make and make it more idiomatic by converting the argument to ~type_: [#switch_ | #checkbox]?

I tried the @as annotation in the arguments, but it doesn’t work well enough with @react.component. @string [@as("switch") #switch_ | #checkbox] works for \"type"=#switch_ and converts it to type: "switch", but in case of @as("type") ~type_:, type_=#checkbox still compiles to type_: "checkbox", which of course does not work with the JS component.

1 Like

I’m not sure of the reason, but for @react.component I believe using ~_type may work.

module Switch = {
  @react.component @module("./Switch")
  external make: (~_type: @string [@as("switch") #switch_ | #checkbox]) => React.element = "default"
}
2 Likes

I think you can simplify it a bit

module Switch = {
  @react.component @module("./Switch")
  external make: (~_type: [#"switch" | #checkbox]) => React.element = "default"
}

let foo = <Switch _type=#"switch" />

Playground

4 Likes

in other posts recently it was asserted that @as wont be supported this way soon. iirc.

1 Like

Thanks! I learned from the docs that @as("type") type_ can rename object fields. Is it also idiomatic to put the underscore before the original name? If so, I would use #_switch to make naming consistent in my bindings.

Aha! Poly variants supports any names in quotes natively, so I would not need to add an underscore. Thanks for the suggestion!

Is it also idiomatic to put the underscore before the original name?

I just suspect this is just a special syntax for ReScript React props that are reserved words.

For example, the same syntax applies to other reserved words such as ~_module, ~_let, ~_external and ~_while. Interestingly it doesn’t apply to ~_switch.

Outside of React component props I’ve typically seen identifier_ being used when the identifier is a reserved word and _identifier to ignore the identifier when it’s a function argument (similar to just using _ alone).

Someone with more knowledge might be able to explain further.