react#MutableRefObject TypeScript Examples

The following examples show how to use react#MutableRefObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
export function useStateRef<T>(value: T): RefObject<T> {
  const ref: MutableRefObject<T> = useRef<T>(value);

  useEffect(() => {
    ref.current = value;
  }, [value]);

  return ref;
}
Example #2
Source File: Hooks.ts    From frontend.ro with MIT License 6 votes vote down vote up
function useOutsideClick(ref: MutableRefObject<HTMLElement>, handler: (e: MouseEvent) => void) {
  useEffect(() => {
    const listener = (event) => {
      if (!ref.current || ref.current.contains(event.target)) {
        return;
      }

      handler(event);
    };

    document.addEventListener('mousedown', listener);
    document.addEventListener('touchstart', listener);

    return () => {
      document.removeEventListener('mousedown', listener);
      document.removeEventListener('touchstart', listener);
    };
  }, [ref, handler]);
}
Example #3
Source File: useNuiEvent.ts    From mojito_pdm with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
useNuiEvent = <T = any>(
  action: string,
  handler: (data: T) => void
) => {
  const savedHandler: MutableRefObject<NuiHandlerSignature<T>> = useRef(noop);

  // When handler value changes set mutable ref to handler val
  useEffect(() => {
    savedHandler.current = handler;
  }, [handler]);

  useEffect(() => {
    const eventListener = (event: MessageEvent<NuiMessageData<T>>) => {
      const { action: eventAction, data } = event.data;

      if (savedHandler.current) {
        if (eventAction === action) {
          savedHandler.current(data);
        }
      }
    };

    window.addEventListener("message", eventListener);
    // Remove Event Listener on component cleanup
    return () => window.removeEventListener("message", eventListener);
  }, [action]);
}
Example #4
Source File: RichTextControls.tsx    From Full-Stack-React-TypeScript-and-Node with MIT License 6 votes vote down vote up
Button = React.forwardRef(
  (
    {
      className,
      active,
      reversed,
      ...props
    }: PropsWithChildren<
      {
        active: boolean;
        reversed: boolean;
      } & BaseProps
    >,
    ref:
      | MutableRefObject<HTMLSpanElement | null>
      | ((instance: HTMLSpanElement | null) => void)
      | null
  ) => (
    <span
      {...props}
      ref={ref}
      className={cx(
        className,
        css`
          cursor: pointer;
          color: ${reversed
            ? active
              ? "white"
              : "#aaa"
            : active
            ? "black"
            : "#aaa"};
        `
      )}
    />
  )
)
Example #5
Source File: useD3.ts    From posthog-foss with MIT License 6 votes vote down vote up
useD3 = (
    renderChartFn: (svg: D3Selector) => void,
    dependencies: any[] = []
): MutableRefObject<any> | null => {
    const ref = useRef<HTMLDivElement>()

    useEffect(
        () => {
            if (ref.current !== undefined) {
                renderChartFn(d3.select(ref.current))
            }
            return () => {}
        },

        dependencies
    )
    return ref
}
Example #6
Source File: get-url.ts    From react-native-use-websocket with MIT License 6 votes vote down vote up
getUrl = async (
  url: string | (() => string | Promise<string>),
  optionsRef: MutableRefObject<Options>,
) => {
  let convertedUrl: string;

  if (typeof url === 'function') {
    convertedUrl = await url();
  } else {
    convertedUrl = url;
  }

  const parsedUrl = optionsRef.current.fromSocketIO ?
    parseSocketIOUrl(convertedUrl) :
    convertedUrl;

  const parsedWithQueryParams = optionsRef.current.queryParams ?
    appendQueryParams(
      parsedUrl,
      optionsRef.current.queryParams,
      optionsRef.current.fromSocketIO,
    ) :
    parsedUrl;

  return parsedWithQueryParams;
}
Example #7
Source File: useClickOutsideModal.ts    From frontend-v1 with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function useClickOutsideModal(
  ref: MutableRefObject<any>,
  callback: Function
) {
  useEffect(() => {
    function handleClickOutside(event: Event) {
      if (ref.current && !ref.current.contains(event.target)) {
        callback();
      }
    }
    // Bind the event listener
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      // Unbind the event listener on clean up
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [ref, callback]);
}
Example #8
Source File: useOverflowWrapper.ts    From hub with Apache License 2.0 6 votes vote down vote up
useOverflowWrapper = (
  wrapperRef: MutableRefObject<HTMLDivElement | null>,
  maxHeight: number,
  itemsLength: number
) => {
  const getHeight = (): number => {
    if (wrapperRef && wrapperRef.current) {
      return wrapperRef.current.offsetHeight;
    } else {
      return 0;
    }
  };

  const checkDimensions = () => {
    const height = getHeight();
    return height > maxHeight;
  };

  const [overflowContainer, setOverflowContainer] = useState<boolean>(() => checkDimensions());

  const handleOverflow = () => {
    setOverflowContainer(checkDimensions());
  };

  useEffect(() => {
    window.addEventListener('resize', throttle(handleOverflow, 200));
    return () => window.removeEventListener('resize', handleOverflow);
  }, []); /* eslint-disable-line react-hooks/exhaustive-deps */

  useLayoutEffect(() => {
    handleOverflow();
  }, []); /* eslint-disable-line react-hooks/exhaustive-deps */

  useEffect(() => {
    handleOverflow();
  }, [itemsLength]); /* eslint-disable-line react-hooks/exhaustive-deps */

  return overflowContainer;
}
Example #9
Source File: useIsMounted.ts    From react-celo with MIT License 6 votes vote down vote up
export function useIsMounted(): MutableRefObject<boolean> {
  const mountedRef = useRef<boolean>(false);
  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
    };
  }, []);
  return mountedRef;
}
Example #10
Source File: Stream.tsx    From stream-react with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Hook for binding event listeners to the player.
 */
function useEvent(
  event: string,
  ref: MutableRefObject<StreamPlayerApi | undefined>,
  callback: EventListener = noop
) {
  useEffect(() => {
    if (!ref.current) return;
    const el = ref.current;
    el.addEventListener(event, callback);
    // clean up
    return () => el.removeEventListener(event, callback);
  }, [callback, event, ref]);
}
Example #11
Source File: Utils.ts    From craft-extension-inspirations with MIT License 6 votes vote down vote up
export function useStateWithRefPair<T>(initValue: T): [T, (v: T) => void, MutableRefObject<T>] {
  const [ value , origSetValue ] = useState<T>(initValue);
  const valueRef = useRef<T>(initValue);

  const setValue = useCallback((v: T) => {
    valueRef.current = v;
    origSetValue(valueRef.current);
  }, [origSetValue]);

  return [ value, setValue, valueRef];
}
Example #12
Source File: useAnalyticsContextData.ts    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function useAnalyticsContextData(
  pushToQueue: PushToQueueFunc,
  sharedPropsRef: MutableRefObject<Partial<AnalyticsEvent>>,
  getPage: () => string,
  durationEventsQueue: MutableRefObject<Map<string, AnalyticsEvent>>,
): AnalyticsContextData {
  return useMemo<AnalyticsContextData>(
    () => ({
      trackEvent(event: AnalyticsEvent) {
        pushToQueue([generateEvent(event, sharedPropsRef, getPage())]);
      },
      trackEventStart(id, event) {
        if (!durationEventsQueue.current.has(id)) {
          durationEventsQueue.current.set(
            id,
            generateEvent(event, sharedPropsRef, getPage()),
          );
        }
      },
      trackEventEnd(id, now = new Date()) {
        const event = durationEventsQueue.current.get(id);
        if (event) {
          durationEventsQueue.current.delete(id);
          event.event_duration =
            now.getTime() - event.event_timestamp.getTime();
          if (window.scrollY > 0 && event.event_name !== 'page inactive') {
            event.page_state = 'active';
          }
          pushToQueue([event]);
        }
      },
    }),
    [sharedPropsRef, getPage, pushToQueue, durationEventsQueue],
  );
}
Example #13
Source File: useStatefulRef.ts    From react-ecs with MIT License 6 votes vote down vote up
export function useStatefulRef<T>(
    inst: T,
): [MutableRefObject<T>, (inst: T) => void] {
    const ref = useRef<T>(inst);
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const [_, setState] = useState({ current: inst });
    const setRef = (current: T) => {
        ref.current = current;
        setState({ current });
    };

    return [ref, setRef];
}
Example #14
Source File: useRefState.ts    From yugong with MIT License 6 votes vote down vote up
function useRefState<S>(
    initialState: S
): [S, Dispatch<SetStateAction<S>>, Readonly<MutableRefObject<S>>] {
    const refState = useRef<S>(initialState);
    const [state, setState] = useState<S>(initialState);
    const updater = useCallback((value: SetStateAction<S>) => {
        const nextState =
            typeof value === 'function'
                ? (value as (v: S) => S)(refState.current)
                : value;
        refState.current = nextState;
        setState(nextState);
    }, []);

    return [state, updater, refState];
}
Example #15
Source File: index.ts    From tobira with Apache License 2.0 6 votes vote down vote up
useOnOutsideClick = (
    ref: MutableRefObject<Node | null>,
    callback: () => void,
): void => {
    useEffect(() => {
        const handler = (event: MouseEvent) => {
            const target = event.target;
            if (ref.current && target instanceof Element && !ref.current.contains(target)) {
                callback();
            }
        };

        document.addEventListener("mousedown", handler);
        return () => document.removeEventListener("mousedown", handler);
    });
}
Example #16
Source File: helper.ts    From geist-ui with MIT License 6 votes vote down vote up
getRect = (ref: MutableRefObject<HTMLElement | null>): ReactiveDomReact => {
  if (!ref || !ref.current) return defaultRect
  const rect = ref.current.getBoundingClientRect()
  return {
    ...rect,
    width: rect.width || rect.right - rect.left,
    height: rect.height || rect.bottom - rect.top,
    top: rect.top + document.documentElement.scrollTop,
    bottom: rect.bottom + document.documentElement.scrollTop,
    left: rect.left + document.documentElement.scrollLeft,
    right: rect.right + document.documentElement.scrollLeft,
  }
}
Example #17
Source File: keychain.tsx    From hive-keychain-mobile with MIT License 6 votes vote down vote up
sendError = (
  tabRef: MutableRefObject<WebView>,
  error: RequestError,
) => {
  console.log('send error');
  tabRef.current.injectJavaScript(
    `window.hive_keychain.onAnswerReceived("hive_keychain_response",${JSON.stringify(
      {success: false, result: null, ...error},
    )})`,
  );
}
Example #18
Source File: useNuiEvent.ts    From fivem-nui-react-lib with GNU General Public License v3.0 6 votes vote down vote up
useNuiEvent = <D = unknown>(app: string, method: string, handler: (r: D) => void): void => {
  const savedHandler: MutableRefObject<(r: D) => void> = useRef();

  // When handler value changes set mutable ref to handler val
  useEffect(() => {
    savedHandler.current = handler;
  }, [handler]);

  useEffect(() => {
    const eventName = eventNameFactory(app, method);
    const eventListener = (event) => {
      if (savedHandler.current && savedHandler.current.call) {
        const { data } = event;
        const newData = data;
        savedHandler.current(newData as D);
      }
    };

    addEventListener(window, eventName, eventListener);
    // Remove Event Listener on component cleanup
    return () => window.removeEventListener(eventName, eventListener);
  }, [app, method]);
}
Example #19
Source File: CommentInput.tsx    From foodie with MIT License 6 votes vote down vote up
CommentInput = forwardRef<HTMLInputElement, IProps>((props, ref) => {
    const { isUpdateMode, isSubmitting, isLoading, ...rest } = props;
    const userPicture = useSelector((state: IRootReducer) => state.auth.profilePicture);

    useEffect(() => {
        ref && (ref as MutableRefObject<HTMLInputElement>).current.focus();
    }, [ref])

    return (
        <div className={`flex items-center w-full`}>
            {!isUpdateMode && <Avatar url={userPicture?.url} className="mr-2 flex-shrink-0" size="sm" />}
            <div className="flex-grow">
                <input
                    {...rest}
                    className={`${isSubmitting && isLoading && 'opacity-50'} dark:bg-indigo-1100 dark:!border-gray-800 dark:text-white`}
                    type="text"
                    readOnly={isLoading || isSubmitting}
                    ref={ref}
                />
                {isUpdateMode && <span className="text-xs text-gray-500 ml-2">Press Esc to Cancel</span>}
            </div>
        </div>
    );
})
Example #20
Source File: useContainerHeight.ts    From TabMerger with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This is useful for dynamically computing  the height of containers relative to some bottom position
 * @param ref The container reference
 * @param updateList A state list that should trigger re-calculation
 * @returns The container's height such that it does not surpass the bottom position
 */
export default function useContainerHeight(ref: MutableRefObject<HTMLDivElement | null>, ...updateList: unknown[]) {
  const [containerHeight, setContainerHeight] = useState(0);

  useEffect(() => {
    if (ref.current) {
      const { top } = ref.current.getBoundingClientRect();
      setContainerHeight(590 - top);
    }
  }, [ref, updateList]);

  return containerHeight;
}
Example #21
Source File: use-observe-width.ts    From admin with MIT License 6 votes vote down vote up
useObserveWidth = (ref: MutableRefObject<any>): number => {
  const [currentWidth, setCurrentWidth] = useState(0)

  const observer = useRef(
    new ResizeObserver((entries) => {
      const { width } = entries[0].contentRect

      setCurrentWidth(width)
    })
  )

  useEffect(() => {
    if (observer?.current && ref?.current) {
      observer.current.observe(ref.current)
    }

    return () => {
      if (observer?.current && ref?.current) {
        observer.current.unobserve(ref?.current)
      }
    }
  }, [ref, observer])

  return currentWidth
}
Example #22
Source File: index.tsx    From g2plot-react with MIT License 6 votes vote down vote up
syncRef = <C extends Options>(
  source: MutableRefObject<BasePlot<C> | null>,
  target?:
    | RefCallback<BasePlot<C> | null>
    | MutableRefObject<BasePlot<C> | null>
) => {
  /* istanbul ignore else */
  if (typeof target === 'function') {
    target(source.current)
  } else if (target) {
    target.current = source.current
  }
}
Example #23
Source File: useNuiEvent.ts    From fivem-react-boilerplate-lua with MIT License 6 votes vote down vote up
useNuiEvent = <T = any>(
  action: string,
  handler: (data: T) => void
) => {
  const savedHandler: MutableRefObject<NuiHandlerSignature<T>> = useRef(noop);

  // Make sure we handle for a reactive handler
  useEffect(() => {
    savedHandler.current = handler;
  }, [handler]);

  useEffect(() => {
    const eventListener = (event: MessageEvent<NuiMessageData<T>>) => {
      const { action: eventAction, data } = event.data;

      if (savedHandler.current) {
        if (eventAction === action) {
          savedHandler.current(data);
        }
      }
    };

    window.addEventListener("message", eventListener);
    // Remove Event Listener on component cleanup
    return () => window.removeEventListener("message", eventListener);
  }, [action]);
}
Example #24
Source File: react.ts    From keen-slider with MIT License 6 votes vote down vote up
export function useKeenSlider<
  T extends HTMLElement,
  O = {},
  P = {},
  H extends string = KeenSliderHooks
>(
  options?: KeenSliderOptions<O, P, H>,
  plugins?: KeenSliderPlugin<O, P, H>[]
): [
  (node: T | null) => void,
  MutableRefObject<KeenSliderInstance<O, P, H> | null>
] {
  const sliderRef = useRef<KeenSliderInstance<O, P, H> | null>(null)
  const optionsCheckedFirst = useRef(false)
  const currentOptions = useRef(options)

  const onRefChange = useCallback((node: T | null) => {
    if (node) {
      currentOptions.current = options
      sliderRef.current = new KeenSlider<O, P, H>(node, options, plugins)
      optionsCheckedFirst.current = false
    } else {
      if (sliderRef.current && sliderRef.current.destroy)
        sliderRef.current.destroy()

      sliderRef.current = null
    }
  }, [])

  useEffect(() => {
    if (!optionsCheckedFirst.current) {
      optionsCheckedFirst.current = true
      return
    }
    if (sliderRef.current) sliderRef.current.update(currentOptions.current)
  }, [checkOptions(currentOptions, options)])

  return [onRefChange, sliderRef]
}
Example #25
Source File: useClickOutside.ts    From web with MIT License 6 votes vote down vote up
/**
 * Triggers callback when user clicks outside the target element.
 *
 * @param ref React ref object with target HTML element.
 * @param callback Callback that will be triggered during the click.
 * @param events Events list that will be used as triggers for outside click.
 * Default: 'mousedown', 'touchstart'
 */
export function useClickOutside<T extends HTMLElement>(
  ref: RefObject<T> | MutableRefObject<T>,
  callback: EventListener,
  events: string[] = DEFAULT_EVENTS
): void {
  const cbRef = useSyncedRef(callback);
  const refRef = useSyncedRef(ref);

  useEffect(() => {
    function handler(this: HTMLElement, event: Event) {
      if (!refRef.current.current) return;

      const { target: evtTarget } = event;
      const cb = cbRef.current;

      if (!evtTarget || (!!evtTarget && !refRef.current.current.contains(evtTarget as Node))) {
        cb.call(this, event);
      }
    }

    events.forEach((name) => on(document, name, handler, { passive: true }));

    return () => {
      events.forEach((name) => off(document, name, handler, { passive: true }));
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [...events]);
}
Example #26
Source File: Overlay.tsx    From kodiak-ui with MIT License 6 votes vote down vote up
Overlay = forwardRef(
  (
    { children, container, ...rest }: OverlayProps,
    ref: MutableRefObject<HTMLDivElement>,
  ) => {
    const { isBrowser } = useSSR()
    const element = (
      <Box
        {...rest}
        ref={ref}
        __base={{
          bg: 'transparent',
          isolation: 'isolate',
        }}
      >
        {children}
      </Box>
    )

    return ReactDOM.createPortal(
      element,
      container || (isBrowser && document.body),
    )
  },
)
Example #27
Source File: player.ts    From spacesvr with MIT License 6 votes vote down vote up
export function createPlayerState(
  bodyApi: Api[1],
  position: MutableRefObject<Vector3>,
  velocity: MutableRefObject<Vector3>,
  lockControls: MutableRefObject<boolean>,
  raycaster: THREE.Raycaster
): PlayerState {
  return {
    position: {
      set: (pos: Vector3) => {
        bodyApi.position.copy(pos);
        position.current.copy(pos);
      },
      get: () => position.current,
    },
    velocity: {
      set: (vec: Vector3) => {
        bodyApi.velocity.copy(vec);
        velocity.current.copy(vec);
      },
      get: () => velocity.current,
    },
    controls: {
      lock: () => (lockControls.current = true),
      unlock: () => (lockControls.current = false),
      isLocked: () => lockControls.current,
    },
    raycaster,
  };
}
Example #28
Source File: Option.tsx    From app-stormkit-io with GNU General Public License v3.0 6 votes vote down vote up
Option: React.FC<Props> = forwardRef(
  (
    { children, className, disabled, value, ...rest },
    ref
  ): React.ReactElement => {
    return (
      <div
        className={cn(
          "border-b border-solid border-gray-80",
          {
            "cursor-pointer hover:bg-gray-90": !disabled,
            "bg-gray-85 text-gray-60": disabled,
          },
          className
        )}
        {...rest}
        ref={ref as MutableRefObject<HTMLDivElement>}
      >
        <div className="flex p-4 items-center">{children}</div>
      </div>
    );
  }
)
Example #29
Source File: useForwardedRef.test.tsx    From use-platform with MIT License 6 votes vote down vote up
describe('useForwardedRef', () => {
  const render = createClientRender()

  test('should copy forward ref as object to mutable ref', () => {
    const ref = createRef<HTMLDivElement>()
    render(<Fixture ref={ref} />)

    expect(ref.current).toBe(screen.getByTestId('container'))
  })

  test('should copy forward ref as fn to mutable ref', () => {
    const ref = createRef<HTMLDivElement | null>() as MutableRefObject<HTMLDivElement | null>
    // eslint-disable-next-line react/jsx-no-bind
    render(<Fixture ref={(node) => (ref.current = node)} />)

    expect(ref.current).toBe(screen.getByTestId('container'))
  })
})