React API Support
Feliz aims to fully support the React API so that it can be used to build React applications standalone with or without Elmish which is mostly responsible for the state and effect management. You get the best of the both worlds when you combine Elmish patterns with those from React using Feliz.
The React API provided by Feliz should feel very familiar to those who already know React and we try as much as possible to map the concepts one-to-one from React and Javascript over to F# so that you can use all the knowledge you have from React in Feliz.
Here follows a full React example with a stateful component using a state variable hook.
0
Show code
module Example.React
open Fable.Core
open Feliz
[<Erase; Mangle(false)>]
type Counter =
[<ReactComponent(true)>]
static member Counter() =
let (count, setCount) = React.useState 0
Html.div [
Html.h1 count
Html.button [
prop.text "Increment"
prop.onClick (fun _ -> setCount(count + 1))
]
]
This example is a direct mapping from the Javascript and React equivalent:
import React, { useState } from 'react';
export default function Counter() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
For those interested this is what the Javascript code looks like when transpiled by Fable:
import React from "react";
import { reactElement, reactApi } from "../../fable_modules/Feliz.2.9.0/Interop.fs.js";
import { ofArray } from "../../fable_modules/fable-library-js.5.0.0-alpha.14/List.js";
export function Counter() {
const patternInput = reactApi.useState(0);
const count = patternInput[0] | 0;
const children = ofArray([reactElement("h1", {
children: [count],
}), reactElement("button", {
children: "Increment",
onClick: (_arg) => {
patternInput[1](count + 1);
},
})]);
return reactElement("div", {
children: reactApi.Children.toArray(Array.from(children)),
});
}
export default Counter;