1 | import { useCallback } from 'react';
|
---|
2 |
|
---|
3 | /**
|
---|
4 | * returns a function that composes multiple refs together.
|
---|
5 | * This can be very useful when you have more hooks that create a ref
|
---|
6 | * that shall be given to a DOM component, but the component only accepts
|
---|
7 | * one ref!
|
---|
8 | *
|
---|
9 | * Example:
|
---|
10 | *
|
---|
11 | * ```
|
---|
12 | * import { useMeasure } from 'react-use';
|
---|
13 | * import { useDrop } from 'react-dnd';
|
---|
14 | *
|
---|
15 | * const MyComponent = () => {
|
---|
16 | * const [measureRef, measure] = useMeasure<HTMLDivElement>();
|
---|
17 | * const [_, dropRef] = useDrop({accept: 'TILE'});
|
---|
18 | * const reactRef = useRef<HTMLDivElement>(null);
|
---|
19 | *
|
---|
20 | * const composedRef = useComposeRef(measureRef, dropRef, reactRef)
|
---|
21 | *
|
---|
22 | * return <div ref={composedRef}/>
|
---|
23 | * }
|
---|
24 | * ```
|
---|
25 | * @param refs a list of refs that shall be composed together
|
---|
26 | * @returns a new ref that shall be given to the component
|
---|
27 | */
|
---|
28 | var useComposeRef = function () {
|
---|
29 | var refs = [];
|
---|
30 | for (var _i = 0; _i < arguments.length; _i++) {
|
---|
31 | refs[_i] = arguments[_i];
|
---|
32 | }
|
---|
33 | return useCallback(function (el) {
|
---|
34 | refs.forEach(function (ref) {
|
---|
35 | if (ref) {
|
---|
36 | if (typeof ref === 'function')
|
---|
37 | ref(el);
|
---|
38 | //@ts-ignore
|
---|
39 | else
|
---|
40 | ref.current = el;
|
---|
41 | }
|
---|
42 | });
|
---|
43 | }, refs);
|
---|
44 | };
|
---|
45 |
|
---|
46 | export { useComposeRef };
|
---|
47 | //# sourceMappingURL=useComposedRef.js.map
|
---|