Skip to content

Instantly share code, notes, and snippets.

@elliotdavies
Created April 24, 2019 13:07
Show Gist options
  • Save elliotdavies/0371b28fc0bb6a865b73183ac5b48f46 to your computer and use it in GitHub Desktop.
Save elliotdavies/0371b28fc0bb6a865b73183ac5b48f46 to your computer and use it in GitHub Desktop.
WIP example for `purescript-react` createRef
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