|
| 1 | +module ComponentsReactHooks.Main where |
| 2 | + |
| 3 | +import Prelude |
| 4 | +import Data.Maybe (Maybe(..), maybe) |
| 5 | +import Effect (Effect) |
| 6 | +import Effect.Exception (throw) |
| 7 | +import React.Basic.DOM (render) |
| 8 | +import React.Basic.DOM as R |
| 9 | +import React.Basic.Events (EventHandler, handler_) |
| 10 | +import React.Basic.Hooks (Component, component, useState, (/\)) |
| 11 | +import React.Basic.Hooks as React |
| 12 | +import Web.HTML (window) |
| 13 | +import Web.HTML.HTMLDocument (body) |
| 14 | +import Web.HTML.HTMLElement (toElement) |
| 15 | +import Web.HTML.Window (document) |
| 16 | + |
| 17 | +main :: Effect Unit |
| 18 | +main = do |
| 19 | + body <- body =<< document =<< window |
| 20 | + case body of |
| 21 | + Nothing -> throw "Could not find body." |
| 22 | + Just b -> do |
| 23 | + container <- mkContainer |
| 24 | + render (container unit) (toElement b) |
| 25 | + |
| 26 | +mkContainer :: Component Unit |
| 27 | +mkContainer = do |
| 28 | + button <- mkButton |
| 29 | + component "Container" \_ -> React.do |
| 30 | + count /\ setCount <- useState 0 |
| 31 | + enabled /\ setEnabled <- useState false |
| 32 | + buttonState /\ setButtonState <- useState Nothing |
| 33 | + let |
| 34 | + handleClick = |
| 35 | + handler_ do |
| 36 | + setCount (_ + 1) |
| 37 | + setEnabled not |
| 38 | + pure |
| 39 | + $ R.div_ |
| 40 | + [ button { enabled, handleClick } |
| 41 | + , R.p_ |
| 42 | + [ R.text ("Button has been toggled " <> show count <> " time(s)") ] |
| 43 | + , R.p_ |
| 44 | + [ R.text |
| 45 | + $ "Last time I checked, the button was: " |
| 46 | + <> (maybe "(not checked yet)" (if _ then "on" else "off") buttonState) |
| 47 | + <> ". " |
| 48 | + , R.button |
| 49 | + { onClick: handler_ (setButtonState \_ -> Just enabled) |
| 50 | + , children: [ R.text "Check now" ] |
| 51 | + } |
| 52 | + ] |
| 53 | + ] |
| 54 | + |
| 55 | +mkButton :: Component { enabled :: Boolean, handleClick :: EventHandler } |
| 56 | +mkButton = |
| 57 | + component "Button" \props -> React.do |
| 58 | + let |
| 59 | + label = if props.enabled then "On" else "Off" |
| 60 | + pure |
| 61 | + $ R.button |
| 62 | + { title: label |
| 63 | + , onClick: props.handleClick |
| 64 | + , children: [ R.text label ] |
| 65 | + } |
0 commit comments