forked from purescript-react/purescript-react-basic-hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathControlledInput.purs
50 lines (45 loc) · 1.56 KB
/
ControlledInput.purs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
module ControlledInput where
import Prelude
import Data.Maybe (Maybe(..), fromMaybe, maybe)
import React.Basic.DOM as R
import React.Basic.DOM.Events (preventDefault, stopPropagation, targetValue, timeStamp)
import React.Basic.Events (EventHandler, handler, merge)
import React.Basic.Hooks (CreateComponent, UseState, Hook, component, fragment, useState, (/\))
import React.Basic.Hooks as React
mkControlledInput :: CreateComponent {}
mkControlledInput = do
component "ControlledInput" \props -> React.do
firstName <- useInput "hello"
lastName <- useInput "world"
pure $ R.form_
[ renderInput firstName
, renderInput lastName
]
where
renderInput input =
fragment
[ R.input { onChange: input.onChange, value: input.value }
, R.p_ [ R.text ("Current value = " <> show input.value) ]
, R.p_ [ R.text ("Changed at = " <> maybe "never" show input.lastChanged) ]
]
useInput
:: String
-> Hook
(UseState { value :: String, lastChanged :: Maybe Number })
{ onChange :: EventHandler
, value :: String
, lastChanged :: Maybe Number
}
useInput initialValue = React.do
{ value, lastChanged } /\ replaceState <- useState { value: initialValue, lastChanged: Nothing }
pure
{ onChange: handler
(preventDefault >>> stopPropagation >>> merge { targetValue, timeStamp })
\{ timeStamp, targetValue } -> do
replaceState \_ ->
{ value: fromMaybe "" targetValue
, lastChanged: Just timeStamp
}
, value
, lastChanged
}