Zaid-Ajaj / Feliz

A fresh retake of the React API in Fable and a collection of high-quality components to build React applications in F#, optimized for happiness
https://zaid-ajaj.github.io/Feliz/
MIT License
540 stars 78 forks source link

Can you provide a sample for using html select and option with Elmish? #517

Closed jchain closed 1 year ago

jchain commented 1 year ago

I try to build a simple app with a html select and option elements. I want to trigger some message when any of the options is selected. But I couldn't figure it out. Here is a screenshot: image

Can you provide some sample code showing a working elmish style select? Thanks!

MangelMaxime commented 1 year ago

An option value in HTML is not an int but a string you are accessing the value coming from value="my-option-value".

It is possible that the int overload, is not accessing ev.target.value but something else.

Also, Browser.Types.Event doesn't have e.Value because, this is not valid JavaScript. In JavaScript, if you want to access the value from an onChange event you do e.target.value.

Here is a working demo:

module Main

open Elmish
open Browser.Dom
open Feliz

type Model =
    {
        SelectedOption : string
    }

type Msg =
    | SelectOption of string

let init () =
    {
        SelectedOption = ""
    }
    , Cmd.none

let update (msg : Msg) (model : Model) =
    match msg with
    | SelectOption newValue ->
        { model with
            SelectedOption = newValue
        }
        , Cmd.none

let view (model : Model) (dispatch : Dispatch<Msg>) =
    Html.select [
        prop.onChange (fun (selectedValue : string) ->
            dispatch (SelectOption selectedValue)
        )
        prop.value model.SelectedOption
        prop.children [
            Html.option [
                prop.value "option-1"
                prop.text "Option n°1"
            ]
            Html.option [
                prop.value "option-2"
                prop.text "Option n°2"
            ]
            Html.option [
                prop.value "option-3"
                prop.text "Option n°3"
            ]
            Html.option [
                prop.value "option-4"
                prop.text "Option n°4"
            ]
        ]
    ]

open Elmish.React

Program.mkProgram init update view
|> Program.withReactBatched "root"
|> Program.run
jchain commented 1 year ago

Oh. Thanks so much! The code works like a charm!