Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Enable Elmish apps in React components instead of full programs #42

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/react.fs
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,36 @@ module Program =
/// Renders React root component inside html element identified by placeholderId using `React.hydrate`.
let withReactHydrate placeholderId (program:Elmish.Program<_,_,_,_>) =
Internal.withReactHydrateUsing lazyView2With placeholderId program

[<RequireQualifiedAccess>]
module Component =
open Elmish
open Fable.React
open Fable.Core.JsInterop

// TODO: Make this compatible with SSR?
let mkComponent<'Props, 'State, 'Msg>
(displayName: string)
(init: 'Props -> 'State)
(update: 'Msg -> 'Props -> 'State -> 'State * Cmd<'Msg>)
(view: 'Props -> 'State -> ('Msg->unit) -> ReactElement)
: (* key: *) string -> 'Props -> ReactElement =

let renderFn (props: 'Props) =
let state = Hooks.useStateLazy(fun () -> init props)
let rec dispatch msg =
state.update(fun state ->
let model, cmdList = update msg props state
// TODO: Is it OK to invoke the commands with recursive dispatch?
for cmd in cmdList do
cmd dispatch
model)
view props state.current dispatch

renderFn?displayName <- displayName
let elemType = ReactElementType.memoWith equalsButFunctions renderFn

fun key props ->
// TODO: Check `key` field is not already in props?
props?key <- key
ReactElementType.create elemType props []