@hrnec06/react_utils 1.9.0 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hrnec06/react_utils",
3
- "version": "1.9.0",
3
+ "version": "1.9.1",
4
4
  "description": "React utilities",
5
5
  "exports": {
6
6
  ".": "./src/index.ts"
@@ -1,5 +1,5 @@
1
- import { Nullable, ReactUtils, RecordValues } from "@hrnec06/util";
2
- import React, { useLayoutEffect, useRef, useState } from "react";
1
+ import { Nullable, Optional, ReactUtils, RecordValues } from "@hrnec06/util";
2
+ import React, { useImperativeHandle, useLayoutEffect, useRef, useState } from "react";
3
3
  import useDefaultValue from "../../hooks/useDefaultValue";
4
4
  import { createPortal } from "react-dom";
5
5
 
@@ -7,21 +7,23 @@ type ShadowRootProps = ReactUtils.Props<{
7
7
  children?: React.ReactNode,
8
8
  shadowConfig?: ShadowRootInit,
9
9
  }, HTMLDivElement>
10
- export default function ShadowRoot({
10
+
11
+ const ShadowRoot = React.forwardRef<Optional<ShadowRoot>, ShadowRootProps>(({
11
12
  children,
12
13
  shadowConfig,
13
14
  ...props
14
- }: ShadowRootProps)
15
- {
16
- const ref = useRef<HTMLDivElement>(null);
15
+ }, ref) => {
16
+ const hostRef = useRef<HTMLDivElement>(null);
17
17
  const shadowAttached = useRef(false);
18
18
 
19
- const [shadow, setShadow] = useState<Nullable<ShadowRoot>>(null);
19
+ const [shadow, setShadow] = useState<Optional<ShadowRoot>>(undefined);
20
+
21
+ useImperativeHandle(ref, () => shadow, [shadow]);
20
22
 
21
23
  useLayoutEffect(() => {
22
- if (!ref.current || shadowAttached.current) return;
24
+ if (!hostRef.current || shadowAttached.current) return;
23
25
 
24
- const shadow = ref.current.attachShadow(shadowConfig ?? { mode: 'open' });
26
+ const shadow = hostRef.current.attachShadow(shadowConfig ?? { mode: 'open' });
25
27
  setShadow(shadow);
26
28
 
27
29
  shadowAttached.current = true;
@@ -31,11 +33,13 @@ export default function ShadowRoot({
31
33
  <div
32
34
  {...props}
33
35
 
34
- ref={ref}
36
+ ref={hostRef}
35
37
  >
36
38
  {
37
39
  shadow ? createPortal(children, shadow) : null
38
40
  }
39
41
  </div>
40
42
  )
41
- }
43
+ });
44
+
45
+ export default ShadowRoot;