Skip to content

Instantly share code, notes, and snippets.

@davesnx
Forked from jordwalke/myComponent.ml
Created December 13, 2021 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davesnx/41ef99231ea9c57fd7901e34256edcd7 to your computer and use it in GitHub Desktop.
Save davesnx/41ef99231ea9c57fd7901e34256edcd7 to your computer and use it in GitHub Desktop.
React OCaml API
open ReactDOM
module MyComponent = struct
(* Component Properties *)
type props = {count: int}
(* Hey, state can be any type! *)
type state = string
(* Initializer *)
let getInitialState props = "neverBeenClicked"
(* Signal handlers - these simply return the next state. *)
let componentWillReceiveProps props (prevProps, prevState) = prevState
let handleClick {props; state; updater} evt = "hasBeenClicked"
(* Render: props and state as arguments, just like we've always wanted *)
let render {props; state; updater} = [
Div.make
~styleString: "Omit to rely on defaults #thanksOCaml - no really, thanks OCaml"
~className: ("P:" ^ props.prefix ^ " S:" ^ state)
~onClick: (updater handleClick)
~children: []
]
end
(* CreateComponent as a Functor. OCaml's (SML's) module system proves to be very powerful *)
module MyComponentClass = React.CreateComponent (MyComponent)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment