Skip to content

Instantly share code, notes, and snippets.

@sgrove
Created October 27, 2017 08:17
Show Gist options
  • Save sgrove/a9baf2c197e362ac620f89b8f69f3e66 to your computer and use it in GitHub Desktop.
Save sgrove/a9baf2c197e362ac620f89b8f69f3e66 to your computer and use it in GitHub Desktop.
external alert : string => unit = "alert" [@@bs.val];
type action =
| Click;
type state = {count: int};
let component = ReasonReact.reducerComponent "Counter";
let make _children => {
...component,
initialState: fun () => {count: 0},
reducer: fun action state =>
switch action {
| Click =>
let oldCount = state.count;
let newCount = oldCount + 1;
ReasonReact.UpdateWithSideEffects
{count: newCount}
(fun {state: {count}} => alert {j|"Updating the counter to $count!"|j})
},
render: fun {reduce, state: {count}} => {
let message = {j|You've clicked the button $count times|j};
<div>
(ReasonReact.stringToElement message)
<div>
<button onClick=(reduce (fun _ => Click))>
(ReasonReact.stringToElement "Click Me")
</button>
</div>
</div>
}
};
type action =
| Click;
type state = {count: int, lastClickDate: option Js.Date.t};
let component = ReasonReact.reducerComponent "Counter";
let make _children => {
...component,
initialState: fun () => {count: 0, lastClickDate: None},
reducer: fun action state =>
switch action {
| Click =>
let oldCount = state.count;
let newCount = oldCount + 1;
ReasonReact.Update {lastClickDate: Some (Js.Date.make ()), count: newCount}
},
render: fun {reduce, state: {count, lastClickDate}} => {
let message = {j|You've clicked the button $count times|j};
let lastClickMessage =
switch lastClickDate {
| None => ""
| Some d =>
let date = Moment.format (Moment.momentWithDate d) "MMMM Do, h:mm:ss.SSS a";
{j|Last clicked on $date.|j}
};
<div>
(ReasonReact.stringToElement message)
<div>
<button onClick=(reduce (fun _ => Click))>
(ReasonReact.stringToElement "Click Me")
</button>
</div>
(ReasonReact.stringToElement lastClickMessage)
</div>
}
};
type action =
| Click;
type state = {count: int, lastClickDate: option Js.Date.t};
let component = ReasonReact.reducerComponent "Counter";
let make _children => {
...component,
initialState: fun () => {count: 0},
reducer: fun action state =>
switch action {
| Click => ReasonReact.Update {count: state.count + 1}
},
render: fun {reduce, state: {count}} => {
let message = {j|You've clicked the button $count times|j};
<div>
(ReasonReact.stringToElement message)
<div>
<button onClick=(reduce (fun _ => Click))>
(ReasonReact.stringToElement "Click Me")
</button>
</div>
</div>
}
};
let component = ReasonReact.statelessComponent "Page";
let make ::message _children => {
...component,
render: fun _self =>
<div> (ReasonReact.stringToElement message) </div>
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment