F#: mixing W# React with W# UI

Ok, recently I’ve tried to port Jordan Marr’s Grouping from Fable to WebSharper.

First of all I understood that we could Inline the call to the React hook

[<Inline "React.useState($0)">]
let UseState (init: 'T) = X<'T * ('T -> unit)>

And Loïc Denuzière, the guru of WebSharper, helped my to define a React Functional Component

let FunctionComponent 
    (f: 'props -> React.Element) (props: 'props) 
    : React.Element =
        (As<Func<obj, React.Element>> f, 
        box props)

Ok, well, now the nice thing is putting together the power of WS.UI with the availability of react components through W# React.
That implies that one can interoperate between W# UI and W# React. For example I can set a WS.UI var from a WS react component! And I am able to do a similar thing also the other way around: I mean setting a React state (let’s say created by the new useState) from WS.UI

The secret for the last thing is trasforming the setState returned from React in a functional F# mutable first class citizen function.

    let mutable setCount  = fun (i:int) ->  ()
module HelloWorld =
    let Example () =
        let count, setCount = React.UseState 0
        React.setCount <- setCount

Here you can find the magic snippet running online from Try W#.

Finally, notice that we can integrate W# React and W# UI also at DOM level in a single hole template.

div [
    on.afterRender ( fun el ->
            ReactHook.HelloWorld.Example ()
        |> WebSharper.React.React.Mount el
] []

One thought on “F#: mixing W# React with W# UI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s