Improved types on element ref objects and their usage

This commit is contained in:
Alejandro Celaya
2023-01-10 20:04:47 +01:00
parent 98e2e57bb2
commit 487c832f5b
7 changed files with 26 additions and 31 deletions

View File

@@ -1,9 +1,9 @@
import { FC, PropsWithChildren, useRef } from 'react';
import { FC, PropsWithChildren } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faInfoCircle as infoIcon } from '@fortawesome/free-solid-svg-icons';
import { UncontrolledTooltip } from 'reactstrap';
import { Placement } from '@popperjs/core';
import { mutableRefToElementRef } from './helpers/components';
import { useElementRef } from './helpers/hooks';
export type InfoTooltipProps = PropsWithChildren<{
className?: string;
@@ -11,14 +11,14 @@ export type InfoTooltipProps = PropsWithChildren<{
}>;
export const InfoTooltip: FC<InfoTooltipProps> = ({ className = '', placement, children }) => {
const ref = useRef<HTMLSpanElement | undefined>();
const ref = useElementRef<HTMLSpanElement>();
return (
<>
<span className={className} ref={mutableRefToElementRef(ref)}>
<span className={className} ref={ref}>
<FontAwesomeIcon icon={infoIcon} />
</span>
<UncontrolledTooltip target={(() => ref.current) as any} placement={placement}>{children}</UncontrolledTooltip>
<UncontrolledTooltip target={ref} placement={placement}>{children}</UncontrolledTooltip>
</>
);
};

View File

@@ -1,5 +0,0 @@
import { MutableRefObject, Ref } from 'react';
export const mutableRefToElementRef = <T>(ref: MutableRefObject<T | undefined>): Ref<T> => (el) => {
ref.current = el ?? undefined; // eslint-disable-line no-param-reassign
};

View File

@@ -1,4 +1,4 @@
import { useState, useRef, EffectCallback, DependencyList, useEffect } from 'react';
import { DependencyList, EffectCallback, useEffect, useRef, useState } from 'react';
import { useSwipeable as useReactSwipeable } from 'react-swipeable';
import { useLocation, useNavigate } from 'react-router-dom';
import { v4 as uuid } from 'uuid';
@@ -91,3 +91,5 @@ export const useDomId = (): string => {
const { current: id } = useRef(`dom-${uuid()}`);
return id;
};
export const useElementRef = <T>() => useRef<T | null>(null);