Skip to content

Commit

Permalink
Add helpers and documentation for referring DOM elements
Browse files Browse the repository at this point in the history
  • Loading branch information
Hi-Angel committed Nov 8, 2024
1 parent be0133c commit e125650
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
1 change: 1 addition & 0 deletions spago.dhall
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ You can edit this file as you like.
, "type-equality"
, "unsafe-coerce"
, "unsafe-reference"
, "web-dom"
, "web-html"
]
, packages = ./packages.dhall
Expand Down
24 changes: 22 additions & 2 deletions src/React/Basic/Hooks.purs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ module React.Basic.Hooks
, writeRef
, useRef
, UseRef
, RefNode
, useRefNode
, useContext
, UseContext
, useEqCache
Expand Down Expand Up @@ -64,7 +66,7 @@ import Data.Bifunctor (rmap)
import Data.Function.Uncurried (Fn2, mkFn2, runFn2)
import Data.Maybe (Maybe)
import Data.Newtype (class Newtype)
import Data.Nullable (Nullable, toMaybe)
import Data.Nullable (Nullable, null, toMaybe)
import Data.Tuple (Tuple(..))
import Data.Tuple.Nested (type (/\), (/\))
import Effect (Effect)
Expand All @@ -75,6 +77,7 @@ import React.Basic (JSX, ReactComponent, ReactContext, Ref, consumer, contextCon
import React.Basic.Hooks.Internal (Hook, HookApply, Pure, Render, bind, discard, coerceHook, unsafeHook, unsafeRenderEffect, type (&))
import Unsafe.Coerce (unsafeCoerce)
import Unsafe.Reference (unsafeRefEq)
import Web.DOM (Node)

--| A simple type alias to clean up component definitions.
type Component props
Expand Down Expand Up @@ -336,6 +339,23 @@ useRef initialValue =
unsafeHook do
runEffectFn1 useRef_ initialValue

-- | A type alias that allows to refer to a DOM node.
type RefNode = Ref (Nullable Node)

-- | A helper around `useRef` that creates a type to be used to refer to DOM nodes.
-- | For example:
-- |
-- | ```purs
-- |
-- | React.component "label" \_ -> React.do
-- | labelRef :: RefNode <- React.useRefNode
-- | pure $ R.label { ref: labelRef
-- | , children: [R.text "hello"]}
-- | ```
-- |
useRefNode :: Hook (UseRef Node) RefNode
useRefNode = unsafeHook $ runEffectFn1 useRef_ null

readRef :: forall a. Ref a -> Effect a
readRef = runEffectFn1 readRef_

Expand Down Expand Up @@ -575,4 +595,4 @@ foreign import useSyncExternalStore3_ :: forall a. EffectFn3
(EffectFn1 (Effect Unit) (Effect Unit)) -- subscribe
(Effect a) -- getSnapshot
(Effect a) -- getServerSnapshot
a
a

0 comments on commit e125650

Please sign in to comment.