|
| 1 | +module ComponentsInputReactHooks.Main where |
| 2 | + |
| 3 | +import Prelude |
| 4 | +import Data.Maybe (Maybe(..)) |
| 5 | +import Effect (Effect) |
| 6 | +import Effect.Exception (throw) |
| 7 | +import Effect.Unsafe (unsafePerformEffect) |
| 8 | +import React.Basic.DOM (render) |
| 9 | +import React.Basic.DOM as R |
| 10 | +import React.Basic.Events (handler_) |
| 11 | +import React.Basic.Hooks |
| 12 | + ( Component |
| 13 | + , Render |
| 14 | + , UseEffect |
| 15 | + , UseRef |
| 16 | + , component |
| 17 | + , readRef |
| 18 | + , useEffectAlways |
| 19 | + , useRef |
| 20 | + , useState |
| 21 | + , writeRef |
| 22 | + , (/\) |
| 23 | + ) |
| 24 | +import React.Basic.Hooks as React |
| 25 | +import Web.HTML (window) |
| 26 | +import Web.HTML.HTMLDocument (body) |
| 27 | +import Web.HTML.HTMLElement (toElement) |
| 28 | +import Web.HTML.Window (document) |
| 29 | + |
| 30 | +main :: Effect Unit |
| 31 | +main = do |
| 32 | + body <- body =<< document =<< window |
| 33 | + case body of |
| 34 | + Nothing -> throw "Could not find body." |
| 35 | + Just b -> do |
| 36 | + container <- mkContainer |
| 37 | + render (container unit) (toElement b) |
| 38 | + |
| 39 | +mkContainer :: Component Unit |
| 40 | +mkContainer = do |
| 41 | + display <- mkDisplay |
| 42 | + component "Container" \_ -> React.do |
| 43 | + parentRenders <- useRenderCount |
| 44 | + state /\ setState <- useState 0 |
| 45 | + pure |
| 46 | + $ R.div_ |
| 47 | + [ R.ul_ |
| 48 | + [ display state |
| 49 | + , display (state * 2) |
| 50 | + , display (state * 3) |
| 51 | + , display (state * 10) |
| 52 | + , display (state * state) |
| 53 | + ] |
| 54 | + , R.button |
| 55 | + { onClick: handler_ (setState (_ + 1)) |
| 56 | + , children: [ R.text "+1" ] |
| 57 | + } |
| 58 | + , R.button |
| 59 | + { onClick: handler_ (setState (_ - 1)) |
| 60 | + , children: [ R.text "-1" ] |
| 61 | + } |
| 62 | + , R.p_ |
| 63 | + [ R.text ("Parent has been rendered " <> show parentRenders <> " time(s)") ] |
| 64 | + ] |
| 65 | + |
| 66 | +mkDisplay :: Component Int |
| 67 | +mkDisplay = |
| 68 | + component "Display" \n -> |
| 69 | + pure |
| 70 | + $ R.div_ |
| 71 | + [ R.text "My input value is: " |
| 72 | + , R.strong_ [ R.text (show n) ] |
| 73 | + ] |
| 74 | + |
| 75 | +useRenderCount :: forall a. Render a (UseEffect Unit (UseRef Int a)) Int |
| 76 | +useRenderCount = React.do |
| 77 | + rendersRef <- useRef 1 |
| 78 | + useEffectAlways do |
| 79 | + renders <- readRef rendersRef |
| 80 | + writeRef rendersRef (renders + 1) |
| 81 | + pure mempty |
| 82 | + let |
| 83 | + renders = unsafePerformEffect (readRef rendersRef) |
| 84 | + pure renders |
0 commit comments