Created
April 24, 2019 13:07
-
-
Save elliotdavies/0371b28fc0bb6a865b73183ac5b48f46 to your computer and use it in GitHub Desktop.
WIP example for `purescript-react` createRef
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React as React | |
import React.DOM as DOM | |
import React.DOM.Props as Props | |
import React.SyntheticEvent (currentTarget) | |
import Web.HTML.HTMLElement (focus) | |
import Unsafe.Coerce (unsafeCoerce) | |
type MyState | |
= { myRef :: React.ReactRef | |
, text :: String | |
} | |
initialState :: React.ReactRef -> MyState | |
initialState myRef | |
= { myRef | |
, text: "" | |
} | |
exampleWithRef :: React.ReactClass {} | |
exampleWithRef = React.component "ExampleWithRef" \this -> do | |
myRef <- React.createRef | |
pure | |
{ state: initialState myRef | |
, render: render this <$> React.getState this | |
, componentDidMount: componentDidMount this | |
} | |
where | |
render this { myRef, text } | |
= DOM.div | |
[] | |
[ DOM.input | |
[ Props._type "text" | |
, Props.value text | |
, Props.onChange $ changeHandler this | |
, Props.ref myRef | |
] | |
] | |
componentDidMount this = do | |
{ myRef } <- React.getState this | |
case React.getRef myRef of | |
Just el -> focus el | |
Nothing -> pure unit | |
changeHandler this event | |
= (unsafeCoerce >>> _.value) <$> (currentTarget event) | |
>>= \ev -> React.modifyState this $ _ { text = ev.target } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment