Custom props hand-writing component without [@react.component]
Binding ReasonReact to ReactJS is never an easy task. Sometimes, props
naming gets in our way. Fortunately, ReasonML will automatically strip out name prefix or suffix with _
so that a prop name such as _open
or _type
turns into a corresponding open
and type
on JavaScript side.
However, there are still restrictions by much of ReasonML naming scheme. For example, a function’s parameters cannot begin with a capital letter, as well as the hyphen
between prop name such as aria-*
.
This demonstrates the problem:
Code above will not compile as aria-label
and ComponentProp
is not conformed to ReasonML parameter naming scheme.
To fix this, we need to create our custom makeProps
and rename the props
key. According to Hand-writing components. All we need is to define makeProps
and props
. The code below shows how to create those two needed.
This code do quite a bit. First, it defines props with [@bs.deriving abstract]
. It turns a record into an Abstract Record Mode. This implies that you cannot create the record compositionally just like a normal record. Instead, it will be created via the auto-generated function of the same name props
. It takes labelled arguments ending with a unit call. This is, conveniently, match the requirement of makeProps
. We can then simply alias it to props
.
The declaration of the type props
is straightforward. [@bs.optional]
says this field can be omitted. And [@bs.as "<name>"]
indicates the translated name on JavaScript side. For _type
we can ignore it as its behaviour will be the same, translating into type
as the result code.
Lastly, the external
make is used to interface to ReactJS Component. We wrapped the props
type in React.component.
Hence, external make: React.component(props('a)) = "default";
Hope this will help if you are struggling with binding ReasonReact to ReactJS.