Conditionally set object fields



ReasonReact has a function called cloneElement, which clones an passed element, and you can pass ~props to it. It is, currently, the only way to set data-* properties of a React element, as stated here:

For data-*, this is a bit trickier; words with - in them aren’t valid in Reason/OCaml. When you do want to write them, e.g. <div data-name="click me" />, use cloneElement as a workaround.

I have a componente that uses data-* props. However, I want to set some of these props only if a certain condition is met.

This is my current code:

ReasonReact.cloneElement(<a className="una-card" href="#" onClick />, ~props={
    "data-fill": (courses |> List.hd).color,
    "data-toggle": "modal",
    "data-target": "#campus-selector-modal"
}, [| |])

I want data-toggle and data-target to be set only if a condition is met (in this case, if courses |> List.length > 1). How can I achieve this?


After struggling a lot, I got to solve this with Js.Obj.assign, this way:

let props = {"data-fill": (courses |> List.hd).color} |> Js.Obj.assign((courses |> List.length) > 1 ? {"data-toggle": "modal", "data-target": "#campus-selector-modal"} : Js.Obj.empty ());

ReasonReact.cloneElement(<a className="una-card" href="#" onClick />, ~props, [| |])

I hope this helps other people with the same question.