Skip to main content

F# in Html

In Feliz you can use F# code directly in your Html structure as it is abstracted into F# native lists. This means you can use all the power of F# to create dynamic and reusable components.

In the following example we define a simple button component that takes a text parameter and renders a styled button with that text.



Show code
module Example.FSharp

open Feliz

Fable.Core.JsInterop.importSideEffects "./fsharp.css"

type ISize =
| Small
| Medium
| Large

type Button =

[<ReactComponent>]
static member Example(text: string, onClick: Browser.Types.MouseEvent -> unit, ?size: ISize) =
let size = defaultArg size Medium
let sizeClass =
match size with
| Small -> "sm"
| Medium -> ""
| Large -> "lg"
Html.button [
prop.text text
prop.onClick onClick
prop.className [ "fsharp-btn"; sizeClass]
]

[<ReactComponent(true)>]
static member Example() =
let fn = fun _ -> Browser.Dom.console.log("Button clicked!")
Html.div [
prop.style [
style.display.flex
style.flexDirection.column
style.alignItems.center
style.justifyContent.center
style.gap 10
]
prop.children [
Button.Example("Submit", fn, size = Large)
Html.br []
Button.Example("Submit", fn, size = Medium)
Html.br []
Button.Example("Submit", fn, size = Small)
]

]

Discriminated Unions

We define the button size as discriminated union type.

type ISize =
| Small
| Medium
| Large

Optional Parameters

We make size an optional parameter with a default value.

static member Example(text: string, onClick: Browser.Types.MouseEvent -> unit, ?size: ISize) =
let size = defaultArg size Medium

info

Because of this we create the component as static member of a class. Using let bindings does not allow for optional parameters

Pattern Matching

We use a match .. with on size to determine the appropriate CSS class to apply.

let sizeClass =
match size with
| Small -> "sm"
| Medium -> ""
| Large -> "lg"

Lambda Functions

We define a function and pass it to the onClick event handler.

let fn = fun _ -> Browser.Dom.console.log("Button clicked!")
// ...
Button.Example("Submit", fn, size = Large)