How to write bindings to a react component that has polymorphic props

For example, consider a component that takes the prop width which can be either a string or a number.

How do I write bindings for that?

1 Like

It really depends.
But I’d suggest to either have two separate bindings for separate usecases or split the binding into two makeProps and one make function.
makeProps would return an abstract type, which needs to be passed to make.

You could also use the same technique just for the props.

That sounds interesting , could you show an example of the second option ?

If using the different types doesn’t result in different behavior, then sometimes it’s easier to just bind to one type. For example, does passing 1 and "1" in JavaScript do the exact same thing? Why not just bind it as either float or string and keep it simple?

Similarly, I’ve seen some JS props that will either accept a value 'a or array<'a>. If an array with only one item produces the exact same behavior as passing one item outside of an array, then it’s easier to just bind to the array<'a> type. (For example, when 1 has the same effect as [1].)

If the behavior is different depending on the type, though, it’s probably better to have two different bindings.

In this case I would be interested in seeing how one would declare different makeProps to one make would look like. Do you happen to know how to accomplish that ?

I’ve written up some possible approaches in the playground.

2 Likes

Thanks a lot for this!

1 Like

You can always use an @unboxed value as well. While it’s a little more verbose to write, it generates great JS output (the dummy functions can easily be eliminated by dead code elimination).

Here is an example of that

5 Likes