ElementTarget
is a union type that represents various kinds of elements that can be targeted in @shined/react-use
.
Ref
or DOM queries face challenges in a Server-Side Rendering (SSR) environment.useTargetElement
.If you are looking for the ElementTarget
type, please refer to ElementTarget Types.
React Hooks often require access to DOM elements to perform operations like clicking outside a component (useClickAway
), hovering (useHover
), or scrolling (useScroll
).
Traditionally, accessing HTML elements in React is mainly done in two ways:
Ref
to an element using ref={ref}
and accessing it in useEffect
and similar places via ref.current
.document
object to obtain elements in useEffect
and similar places, like querySelector
.While these methods are effective, they pose challenges in an SSR environment, as direct access to elements or browser-specific objects during rendering is not possible. Instead, developers must access these elements or objects on the client-side using useEffect
or Ref
. Moreover, developers often wish to access elements directly via passing Ref
, which is a common requirement in many Hooks and daily use scenarios.
To address these issues, we created the useTargetElement
Hook, which simplifies the process of obtaining the target element. This Hook returns a React Ref
containing the target element:
It can accept a Getter function as input to avoid SSR-related errors and also supports a Ref
containing the element to enhance Developer Experience (DX) and accommodate a wide range of scenarios.
This Hook has been used in many core functionalities of @shined/react-use
, such as useClickAway
, useHover
, and useScroll
, representing best practices for developers needing to access elements within their Hooks.
The "đĨ" prefix indicates it can be a Getter function, especially useful in SSR. The "âī¸" prefix indicates it can be a Ref
containing it.
#id
, .class.subclass
, tag
, etc.