react#Ref TypeScript Examples

The following examples show how to use react#Ref. 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: ProfileImageLink.tsx    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
function ProfileImageLinkComponent(
  { picture = { size: 'large' }, ...props }: ProfileImageLinkProps,
  ref?: Ref<HTMLAnchorElement>,
): ReactElement {
  return (
    <ProfileLink {...props} ref={ref}>
      <ProfilePicture
        {...picture}
        ref={null}
        user={props.user}
        nativeLazyLoading
      />
    </ProfileLink>
  );
}
Example #2
Source File: RcClickTrigger.tsx    From fe-foundation with Apache License 2.0 6 votes vote down vote up
RcClickTrigger = forwardRef(function <T> (
    props: IRcClickTriggerProps<T>,
    ref: Ref<HTMLSpanElement>
): JSX.Element {

    const {
        children,
        disabled,
        data,
        captureOptions,
        triggerId,
        disableToggleClose,
        ...extra
    } = props;

    const triggerRef = useRef<HTMLSpanElement>(null);

    useImperativeHandle(ref, () => triggerRef.current as HTMLSpanElement, [triggerRef.current]);

    const [clickTrigger, result] = useTrigger(
        (...args) => new Trigger(...args),
        {disabled, captureOptions, data, disableToggleClose},
        triggerRef,
        'click',
        triggerId
    );

    return (
        <span {...extra} ref={triggerRef} data-rc-id={`trigger___${clickTrigger.getId()}`}>
            {typeof children === 'function' ? children(result) : children}
        </span>
    );
}) as <T>(props: IRcClickTriggerProps<T>) => JSX.Element
Example #3
Source File: ProfilePicture.tsx    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
function ProfilePictureComponent(
  {
    user,
    size = 'xlarge',
    className,
    nativeLazyLoading,
    ...props
  }: ProfilePictureProps,
  ref?: Ref<HTMLImageElement>,
): ReactElement {
  if (nativeLazyLoading) {
    return (
      <img
        {...props}
        ref={ref}
        src={user.image}
        alt={`${user.username}'s profile`}
        className={classNames(sizeClasses[size], className)}
        loading="lazy"
      />
    );
  }

  return (
    <LazyImage
      {...props}
      ref={ref}
      imgSrc={user.image}
      imgAlt={`${user.username}'s profile`}
      className={classNames(sizeClasses[size], className)}
      fallbackSrc={fallbackImages.avatar}
    />
  );
}
Example #4
Source File: Card.tsx    From baleen3 with Apache License 2.0 6 votes vote down vote up
Card = forwardRef(
  ({ children, ...props }: CardProps, ref: Ref<HTMLDivElement>) => (
    <Box p={2} width={{ sm: 1, md: 1 / 2 }}>
      <StyledCard ref={ref} {...props}>
        {children}
      </StyledCard>
    </Box>
  )
)
Example #5
Source File: BroadcastChannel.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
export function LegacyBroadcastChannel(
  { channelName, onMessage }: BroadcastChannelProps,
  ref: Ref<Pick<BroadcastChannel, "postMessage">>
): React.ReactElement {
  const channelRef = useRef<BroadcastChannel>();
  const polyfillRef = useRef<typeof BroadcastChannel>();

  useImperativeHandle(ref, () => ({
    postMessage(message: unknown) {
      return channelRef.current?.postMessage(message);
    },
  }));

  useEffect(() => {
    const handleMessage = (event: MessageEvent): void => {
      // When using polyfill, the message event is the message data itself.
      onMessage(window.BroadcastChannel ? event.data : event);
    };
    (async () => {
      polyfillRef.current = await getBroadcastChannelPolyfill();
      channelRef.current = channelName
        ? new polyfillRef.current(channelName)
        : null;
      channelRef.current?.addEventListener("message", handleMessage);
    })();
    return () => {
      channelRef.current?.close();
      channelRef.current?.removeEventListener("message", handleMessage);
    };
  }, [channelName, onMessage]);

  return null;
}
Example #6
Source File: hooks.ts    From frontegg-react with MIT License 6 votes vote down vote up
export function useCombinedRefs<T extends any>(refs: Ref<T>[]): Ref<T> {
  return useCallback(
    (node: T) => {
      refs.forEach((ref) => {
        if (!ref) return;
        if (typeof ref === 'function') {
          return ref(node);
        }
        if (typeof ref === 'object') {
          (ref as any).current = node;
        }
      });
    },
    [refs]
  );
}
Example #7
Source File: index.tsx    From react-bootstrap-country-select with MIT License 6 votes vote down vote up
ListItem = forwardRef(({
  classPrefix,
  country,
  country: {
    flag,
  },
  active,
  countryLabelFormatter,
  flags,
  onClick,
}: ListItemProps, ref: Ref<HTMLLIElement>) => {

  const className = classNames([
    `${classPrefix}__list-item`,
    active && 'active',
  ]);

  return (
    <li
      className={className}
      onClick={onClick}
      ref={ref}
    >
              
      {flags ? <span className={`${classPrefix}__flag`}>{flag}</span> : null}
  
      {countryLabelFormatter(country)}
  
    </li>
  );

})
Example #8
Source File: index.tsx    From plasmic with MIT License 6 votes vote down vote up
SliderWrapper = forwardRef(function SliderWrapper_(
  { editingSlide, ...props }: Settings & { editingSlide?: number },
  userRef?: Ref<Slider>
) {
  const slider = useRef<Slider>(null);
  useEffect(() => {
    if (editingSlide !== undefined) {
      slider.current!.slickGoTo(editingSlide);
    }
  }, [editingSlide]);
  return <Slider ref={composeRefs(slider, userRef)} {...props} />;
})
Example #9
Source File: Hoverable.tsx    From iotexplorer-h5-panel-demo with MIT License 6 votes vote down vote up
function HoverableRaw<P extends keyof JSX.IntrinsicElements = 'span'>(
  props: HoverablePropsType<P>,
  ref: Ref<JSX.IntrinsicElements[P]>
) {
  const {
    parent,
    children,
    className,
    disabled,
    hoverClass = 'hover',
    ...htmlProps
  } = props;

  const [hover, setHover] = useState(false);

  useEffect(() => {
    if (disabled) {
      setHover(false);
    }
  }, [disabled]);

  return React.createElement(
    parent || 'div',
    {
      ref,
      className: classNames(className, {
        [hoverClass]: !disabled && hover,
      }),
      onTouchStart: () => !disabled && setHover(true),
      onTouchMove: () => !disabled && setHover(false),
      onTouchEnd: () => !disabled && setHover(false),
      ...htmlProps,
    },
    children
  );
}
Example #10
Source File: Link.tsx    From rocon with MIT License 6 votes vote down vote up
RawLink = <Match,>(
  { route, match, ...props }: LinkProps<Match>,
  ref: Ref<HTMLAnchorElement | null>
): ReactElement | null => {
  const parentRoute = useContext(RouteContext);
  const navigate = useNavigate();
  const href = useMemo(() => {
    const baseLocation = getNavigationBaseLocation(parentRoute, route);
    const location = getRouteRecordLocation(
      route,
      (match || {}) as Match,
      baseLocation
    );
    return locationToURL(location);
  }, [route, match, parentRoute]);
  return (
    <a
      ref={ref}
      href={href}
      onClick={(e) => {
        if (!isModifiedEvent(e)) {
          e.preventDefault();
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          (navigate as any)(route, match);
        }
      }}
      {...props}
    />
  );
}
Example #11
Source File: useForkRef.ts    From docs-components with MIT License 6 votes vote down vote up
export function useForkRef<T>(refA?: Ref<T> | null, refB?: Ref<T> | null): Ref<T> | null {
    return useMemo(() => {
        if (refA === null && refB === null) {
            return null;
        }

        return (value) => {
            setRef(value, refA);
            setRef(value, refB);
        };
    }, [refA, refB]);
}
Example #12
Source File: BigDecimalInput.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
BigDecimalInput = forwardRef((props: InputNumberProps, ref: Ref<typeof InputNumber>) => {
  return (
    <InputNumber className={styles.inputNumberField}
                 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                 // @ts-ignore ref is missing in typings, but it does actually work
                 ref={ref}
                 stringMode={true}
                 {...props}
    />
  );
})
Example #13
Source File: Button.tsx    From crowdsource-dataplatform with MIT License 6 votes vote down vote up
Button = ({ variant = 'primary', ...rest }: ButtonProps, ref: Ref<HTMLObjectElement>) => {
  const { name, className } = getVariantMapping(variant);

  return (
    <ReactBootstrapButton
      data-testid="Button"
      {...rest}
      ref={ref}
      variant={name}
      className={classnames(rest.className, className)}
    />
  );
}
Example #14
Source File: index.tsx    From prism-frontend with MIT License 6 votes vote down vote up
Input = forwardRef(
  ({ value, onClick }: InputProps, ref?: Ref<HTMLButtonElement>) => {
    return (
      <Button variant="outlined" onClick={onClick} ref={ref}>
        {value}
      </Button>
    );
  },
)
Example #15
Source File: UuidInput.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
UuidInput = forwardRef((props: InputProps, ref: Ref<Input>) => {
  return (
    <InputWithMask mask='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
                   formatChars={{
                     'x': '[0-9a-fA-F]'
                   }}
                   ref={ref}
                   {...props}
    />
  );
})
Example #16
Source File: BarChartStepperButton.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
BarChartStepperButton = forwardRef(
  (
    {
      name,
      children,
      ...buttonBaseProps
    }: PropsWithChildren<BarChartStepperButtonProps>,
    ref: Ref<HTMLButtonElement>,
  ) => {
    const classes = useStyles();
    return (
      <ButtonBase
        ref={ref}
        classes={classes}
        disableRipple
        data-testid={`bar-chart-stepper-button-${name}`}
        {...buttonBaseProps}
      >
        {children}
      </ButtonBase>
    );
  },
)
Example #17
Source File: Select.tsx    From amazon-chime-sdk-smart-video-sending-demo with Apache License 2.0 6 votes vote down vote up
Select = forwardRef((props: SelectProps, ref: Ref<HTMLSelectElement>) => (
  <StyledSelectInput
    className="Select"
    data-testid='select'
    ref={ref}
    {...props}
  >
    {renderOptions(props.options)}
  </StyledSelectInput>
))
Example #18
Source File: CharInput.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
CharInput = forwardRef((props: InputProps, ref: Ref<Input>) => {
  const {className = '', ...rest} = props;
  return (
    <Input 
      {...rest}
      ref={ref}
      maxLength={1}
      className={classNames(
        className,
        styles.charInputField
      )} 
    />
  );
})
Example #19
Source File: useForkRef.test.ts    From use-platform with MIT License 5 votes vote down vote up
function renderForkRefHook(refA: Ref<any>, refB: Ref<any>) {
  const { result } = renderHook(() => useForkRef(refA, refB))

  return result.current
}
Example #20
Source File: BroadcastChannel.spec.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
describe("BroadcastChannelComponent", () => {
  it("should work", async () => {
    const channelName = "my-channel";

    const onMessageA = jest.fn();
    const refA: Ref<Pick<BroadcastChannel, "postMessage">> = { current: null };
    mount(
      <BroadcastChannelComponent
        channelName={channelName}
        onMessage={onMessageA}
        ref={refA}
      />
    );

    const onMessageB = jest.fn();
    const refB: Ref<Pick<BroadcastChannel, "postMessage">> = { current: null };
    const wrapperB = mount(
      <BroadcastChannelComponent
        channelName={channelName}
        onMessage={onMessageB}
        ref={refB}
      />
    );

    const onMessageC = jest.fn();
    const refC: Ref<Pick<BroadcastChannel, "postMessage">> = { current: null };
    mount(
      <BroadcastChannelComponent
        channelName="another-channel"
        onMessage={onMessageC}
        ref={refC}
      />
    );

    const onMessageD = jest.fn();
    const refD: Ref<Pick<BroadcastChannel, "postMessage">> = { current: null };
    mount(
      <BroadcastChannelComponent
        channelName={null}
        onMessage={onMessageD}
        ref={refD}
      />
    );

    await (global as any).flushPromises();

    refA.current.postMessage({
      hello: "world",
    });
    expect(onMessageA).not.toBeCalled();
    expect(onMessageB).toBeCalledTimes(1);
    expect(onMessageC).not.toBeCalled();
    expect(onMessageD).not.toBeCalled();

    refA.current.postMessage({
      hello: "better world",
    });
    expect(onMessageB).toBeCalledTimes(2);

    wrapperB.unmount();
    refA.current.postMessage({
      hello: "empty world",
    });
    expect(onMessageB).toBeCalledTimes(2);
  });
});
Example #21
Source File: Transition.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
Transition = forwardRef(function Transition(
  props: { children?: React.ReactElement<any, any> } & TransitionProps,
  ref: Ref<unknown>,
) {
  return <Slide direction="up" ref={ref} {...props} />;
})
Example #22
Source File: index.tsx    From exevo-pan with The Unlicense 5 votes vote down vote up
Listbox = (
  {
    className,
    children,
    highlightedIndex,
    selectedIndex = new Set<number>([]),
    onSelectOption,
    ...props
  }: ListboxProps,
  refProp: Ref<HTMLDivElement>,
) => {
  const currentActiveDescendantId = useMemo(
    () => indexToId(highlightedIndex, props.id),
    [highlightedIndex, props.id],
  )
  return (
    <div
      ref={refProp}
      role="listbox"
      aria-activedescendant={currentActiveDescendantId}
      tabIndex={-1}
      className={clsx(
        'custom-scrollbar bg-surface overflow-y-auto overflow-x-hidden rounded-md shadow-lg',
        className,
      )}
      {...props}
    >
      {Children.map(children, (child, index) => {
        if (!isValidElement(child)) return child
        if (typeof child.type === 'string') return child

        return cloneElement(child, {
          id: indexToId(index, props.id),
          highlighted: highlightedIndex === index,
          'aria-selected': selectedIndex.has(index),
          onClick: onSelectOption,
        })
      })}
    </div>
  )
}
Example #23
Source File: GeneralClipboard.spec.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
describe("GeneralClipboard", () => {
  it("should work", () => {
    const onClipboardChange = jest.fn();
    const ref: Ref<{ setClipboardImmediately(clipboard: unknown): void }> = {
      current: null,
    };
    mount(
      <GeneralClipboard
        storageKey={storageKey}
        onClipboardChange={onClipboardChange}
        ref={ref}
      />
    );
    expect(onClipboardChange).toBeCalledTimes(1);
    expect(onClipboardChange).toBeCalledWith({
      type: "COPY",
      sourceId: "node-1",
    });

    // Set clipboard to the same data.
    act(() => {
      ref.current.setClipboardImmediately({
        type: "COPY",
        sourceId: "node-1",
      });
    });
    expect(onClipboardChange).toBeCalledTimes(1);

    // Set clipboard to another data.
    act(() => {
      ref.current.setClipboardImmediately({
        type: "CUT",
        sourceInstanceId: "node-1",
      });
    });
    expect(onClipboardChange).toBeCalledTimes(2);
    expect(onClipboardChange).toHaveBeenNthCalledWith(2, {
      type: "CUT",
      sourceInstanceId: "node-1",
    });

    // Set clipboard to undefined.
    act(() => {
      ref.current.setClipboardImmediately(undefined);
    });
    expect(onClipboardChange).toBeCalledTimes(3);
    expect(onClipboardChange).toHaveBeenNthCalledWith(3, null);
  });

  it("should work without storageKey", () => {
    const onClipboardChange = jest.fn();
    const ref: Ref<{ setClipboardImmediately(clipboard: unknown): void }> = {
      current: null,
    };
    mount(
      <GeneralClipboard
        storageKey={null}
        onClipboardChange={onClipboardChange}
        ref={ref}
      />
    );
    expect(onClipboardChange).not.toBeCalled();

    act(() => {
      ref.current.setClipboardImmediately({
        type: "COPY",
        sourceId: "node-1",
      });
    });
    expect(onClipboardChange).toBeCalledTimes(1);
    expect(onClipboardChange).toBeCalledWith({
      type: "COPY",
      sourceId: "node-1",
    });
  });
});
Example #24
Source File: Table.tsx    From frontegg-react with MIT License 5 votes vote down vote up
Table = forwardRef((props, ref) =>
  React.createElement(ElementsFactory.getElement('Table'), { ...props, ref } as any)
) as <T extends object = {}>(props: TableProps<T> & { ref?: Ref<HTMLTableElement> }) => ReactElement
Example #25
Source File: index.tsx    From g2plot-react with MIT License 5 votes vote down vote up
BaseChart = <C extends Options>(
  props: BaseChartProps<C>,
  ref?: Ref<HTMLDivElement | null>
) => {
  const {
    chart: Chart,
    style,
    className,
    chartRef: chart,
    onReady,
    ...restProps
  } = props
  const chartRef = useRef<BasePlot<C> | null>(null)
  const configRef = useRef<ChartConfig>()
  const containerRef = useRef<HTMLDivElement>(null)
  const isFirstRenderRef = useRef<boolean>(true)
  const dataRef = useRef<Record<string, any>[]>([])

  useImperativeHandle(ref, () => containerRef.current)

  useEffect(() => {
    const { current: container } = containerRef
    /* istanbul ignore else */
    if (container) {
      const { data, ...config } = restProps as Options
      configRef.current = cloneDeep(config)
      const normalizedData = data || []
      dataRef.current = normalizedData
      const mergedConfig = {
        ...config,
        data: normalizedData,
      } as any
      chartRef.current = new Chart(container, mergedConfig)
      chartRef.current.render()
    }
    syncRef(chartRef, chart)
    if (chartRef.current) {
      onReady?.(chartRef.current)
    }
    return () => {
      /* istanbul ignore else */
      if (chartRef.current) {
        chartRef.current.destroy()
        chartRef.current = null
        syncRef(chartRef, chart)
      }
    }
    // eslint-disable-next-line
  }, [])

  useEffect(() => {
    const { current: chart } = chartRef
    /* istanbul ignore else */
    if (chart) {
      // avoid update in first time
      if (!isFirstRenderRef.current) {
        const { data, ...config } = restProps as Options
        const normalizedData = data || []
        if (!isEqual(config, configRef.current) || isEmpty(dataRef.current)) {
          configRef.current = cloneDeep(config)
          const mergedConfig = {
            ...config,
            data: normalizedData,
          }

          chart.update(mergedConfig as any)
          chart.render()
        } else {
          chart.changeData(normalizedData)
        }
        dataRef.current = normalizedData
      } else {
        isFirstRenderRef.current = false
      }
    }
  }, [restProps])

  return <div style={style} className={className} ref={containerRef} />
}
Example #26
Source File: Link.tsx    From frontend with MIT License 5 votes vote down vote up
NextLink = ({ href, as, prefetch, ...props }: LinkProps, ref: Ref<LinkRef>) => (
  <Link href={href} as={as} prefetch={prefetch} passHref>
    <MuiLink ref={ref} {...props} />
  </Link>
)
Example #27
Source File: Menu.tsx    From realayers with Apache License 2.0 5 votes vote down vote up
Menu: FC<Partial<MenuProps & { ref?: Ref<HTMLDivElement> }>> =
  forwardRef(
    (
      {
        reference,
        children,
        style,
        className,
        placement,
        closeOnEscape,
        open,
        appendToBody,
        closeOnBodyClick,
        maxHeight,
        autofocus,
        onClose,
        onMouseEnter,
        onMouseLeave
      },
      ref: Ref<HTMLDivElement>
    ) => {
      const id = useId();

      return (
        <ConnectedOverlay
          open={open}
          closeOnBodyClick={closeOnBodyClick}
          appendToBody={appendToBody}
          reference={reference}
          placement={placement}
          closeOnEscape={closeOnEscape}
          content={() => (
            <motion.div
              ref={ref}
              initial={{ opacity: 0, y: -10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -10 }}
              className={classNames(css.container, className)}
              style={style}
              onMouseEnter={onMouseEnter}
              onMouseLeave={onMouseLeave}
            >
              {autofocus && (
                <FocusTrap
                  focusTrapOptions={{
                    escapeDeactivates: true,
                    clickOutsideDeactivates: true,
                    fallbackFocus: `#${id}`
                  }}
                >
                  <div
                    id={id}
                    className={css.inner}
                    tabIndex={-1}
                    style={{ maxHeight }}
                  >
                    {children}
                  </div>
                </FocusTrap>
              )}
              {!autofocus && <div className={css.inner}>{children}</div>}
            </motion.div>
          )}
          onClose={onClose}
        />
      );
    }
  )
Example #28
Source File: anchor.tsx    From website with Apache License 2.0 5 votes vote down vote up
Anchor = ({ children }: { children: string | string[] }) => {
  const context = useContext(AnchorContext);
  const ref = useRef<HTMLElement | null>(null);

  const id = (
    typeof children === 'string'
      ? [children.trim().split(' ').join('-')]
      : // Somehow children arrays could END with a space.
        children.filter(
          (text, index) => !(index === children.length - 1 && text === ' ')
        )
  )
    .filter((child) => typeof child === 'string')
    .map((child) => child.trim().split(' ').join('-'))
    .join('-')
    .toLowerCase();

  useEffect(() => {
    context.listen(ref.current);

    return () => {
      context.unlisten(ref.current);
    };
  }, [context, id]);

  return (
    <a
      ref={ref as Ref<HTMLAnchorElement>}
      href={`#${id}`}
      id={id}
      css={{
        color: 'currentColor',
        textDecoration: 'none',
        position: 'relative',
        ':before': {
          opacity: 0,
          content: '?',
          position: 'absolute',
          left: '-4rem',
          fontSize: '3rem',
          transform: 'translateX(1rem)',
          transition: 'opacity 100ms, transform 100ms',
          paddingRight: '5rem',
          top: 0,
          bottom: 0,
          display: 'flex',
          alignItems: 'center',
        },
        ':hover,:focus': {
          ':before': {
            opacity: 1,
            transform: 'none',
          },
        },
      }}>
      {children}
    </a>
  );
}
Example #29
Source File: LazyImage.tsx    From apps with GNU Affero General Public License v3.0 5 votes vote down vote up
function LazyImageComponent(
  {
    imgSrc,
    imgAlt,
    eager,
    className,
    ratio,
    background,
    fallbackSrc,
    children,
    absolute = false,
    fit = 'cover',
    ...props
  }: LazyImageProps,
  ref?: Ref<HTMLImageElement>,
): ReactElement {
  // const { asyncImageSupport } = useContext(ProgressiveEnhancementContext);
  const baseImageClass = `absolute block inset-0 w-full h-full m-auto ${
    fit === 'cover' ? 'object-cover' : 'object-contain'
  }`;
  let imageProps: ImgHTMLAttributes<HTMLImageElement> & {
    'data-src'?: string;
  };
  if (eager) {
    imageProps = { src: imgSrc, className: baseImageClass };
  } else if (asyncImageSupport) {
    imageProps = { src: imgSrc, loading: 'lazy', className: baseImageClass };
  } else {
    imageProps = {
      className: `lazyload ${baseImageClass}`,
      'data-src': imgSrc,
    };
  }

  const onError = (event: SyntheticEvent<HTMLImageElement>): void => {
    if (fallbackSrc) {
      // eslint-disable-next-line no-param-reassign
      event.currentTarget.src = fallbackSrc;
    }
  };

  return (
    <div
      {...props}
      className={classNames(
        className,
        absolute ? 'absolute' : 'relative',
        'overflow-hidden',
      )}
      style={{ background, ...props.style }}
      ref={ref}
    >
      {ratio && <div style={{ paddingTop: ratio, zIndex: -1 }} />}
      <img {...imageProps} alt={imgAlt} key={imgSrc} onError={onError} />
      {children}
    </div>
  );
}