main
Last change
on this file since 0c6b92a was d565449, checked in by stefan toskovski <stefantoska84@…>, 3 months ago |
Update repo after prototype presentation
|
-
Property mode
set to
100644
|
File size:
1.3 KB
|
Rev | Line | |
---|
[d565449] | 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
|
---|
Note:
See
TracBrowser
for help on using the repository browser.