@@ -34,6 +34,8 @@ module React.Basic.Hooks
3434 , writeRef
3535 , useRef
3636 , UseRef
37+ , RefNode
38+ , useRefNode
3739 , useContext
3840 , UseContext
3941 , useEqCache
@@ -64,7 +66,7 @@ import Data.Bifunctor (rmap)
6466import Data.Function.Uncurried (Fn2 , mkFn2 , runFn2 )
6567import Data.Maybe (Maybe )
6668import Data.Newtype (class Newtype )
67- import Data.Nullable (Nullable , toMaybe )
69+ import Data.Nullable (Nullable , null , toMaybe )
6870import Data.Tuple (Tuple (..))
6971import Data.Tuple.Nested (type (/\), (/\))
7072import Effect (Effect )
@@ -75,6 +77,7 @@ import React.Basic (JSX, ReactComponent, ReactContext, Ref, consumer, contextCon
7577import React.Basic.Hooks.Internal (Hook , HookApply , Pure , Render , bind , discard , coerceHook , unsafeHook , unsafeRenderEffect , type (&))
7678import Unsafe.Coerce (unsafeCoerce )
7779import Unsafe.Reference (unsafeRefEq )
80+ import Web.DOM (Node )
7881
7982-- | A simple type alias to clean up component definitions.
8083type Component props
@@ -336,6 +339,23 @@ useRef initialValue =
336339 unsafeHook do
337340 runEffectFn1 useRef_ initialValue
338341
342+ -- | A type alias that allows to refer to a DOM node.
343+ type RefNode = Ref (Nullable Node )
344+
345+ -- | A helper around `useRef` that creates a type to be used to refer to DOM nodes.
346+ -- | For example:
347+ -- |
348+ -- | ```purs
349+ -- | …
350+ -- | React.component "label" \_ -> React.do
351+ -- | labelRef :: RefNode <- React.useRefNode
352+ -- | pure $ R.label { ref: labelRef
353+ -- | , children: [R.text "hello"]}
354+ -- | ```
355+ -- |
356+ useRefNode :: Hook (UseRef Node ) RefNode
357+ useRefNode = unsafeHook $ runEffectFn1 useRef_ null
358+
339359readRef :: forall a . Ref a -> Effect a
340360readRef = runEffectFn1 readRef_
341361
@@ -575,4 +595,4 @@ foreign import useSyncExternalStore3_ :: forall a. EffectFn3
575595 (EffectFn1 (Effect Unit ) (Effect Unit )) -- subscribe
576596 (Effect a ) -- getSnapshot
577597 (Effect a ) -- getServerSnapshot
578- a
598+ a
0 commit comments