react#ForwardedRef TypeScript Examples

The following examples show how to use react#ForwardedRef. 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: useForwardRef.ts    From ChatUI with MIT License 6 votes vote down vote up
export default function useForwardRef<T>(ref: ForwardedRef<T>) {
  const targetRef = useRef<T>(null);

  useEffect(() => {
    if (!ref) return;

    if (typeof ref === 'function') {
      ref(targetRef.current);
    } else {
      // eslint-disable-next-line no-param-reassign
      ref.current = targetRef.current;
    }
  }, [ref]);

  return targetRef;
}
Example #2
Source File: index.tsx    From react-ecs with MIT License 6 votes vote down vote up
Plane = forwardRef((props: GroupProps & PlaneProps, ref: ForwardedRef<ReactNode>) => {
    const { render, ...groupProps } = props
    return (
        <Entity>
            <Neighbor />
            <Velocity />
            <Acceleration />
            <ThreeView>
                <group ref={ref} {...groupProps} dispose={null}>
                    {render()}
                </group>
            </ThreeView>
        </Entity>
    )
})
Example #3
Source File: index.tsx    From formik-chakra-ui with MIT License 6 votes vote down vote up
InputControl: FC<InputControlProps> = React.forwardRef(
  (props: InputControlProps, ref: ForwardedRef<HTMLInputElement>) => {
    const { name, label, inputProps, ...rest } = props;
    const [field] = useField(name);

    return (
      <FormControl name={name} label={label} {...rest}>
        <Input {...field} id={name} {...inputProps} ref={ref} />
      </FormControl>
    );
  }
)
Example #4
Source File: useForwardedRef.ts    From use-platform with MIT License 6 votes vote down vote up
/**
 * Copies forwarded ref to mutable ref object.
 *
 * @example
 * const Component = forwardRef<HTMLDivElement>((_, forwardedRef) => {
 *   const ref = useRef<HTMLDivElement>(null)
 *   useForwardedRef(ref, forwardedRef)
 *
 *   return <div ref={ref} />
 * })
 */
export function useForwardedRef<T>(ref: RefObject<T>, forwardedRef: ForwardedRef<T>): void {
  useImperativeHandle<T | null, T | null>(forwardedRef, () => ref.current)
}
Example #5
Source File: Loader.tsx    From frames with Mozilla Public License 2.0 5 votes vote down vote up
WithForwardingRef = <Props extends { [_: string]: any }, T extends Element>(BaseComponent: ComponentType<Props>) =>
    react.forwardRef((props: Props, ref: ForwardedRef<T>) => <BaseComponent {...props} forwardRef={ref}/>)
Example #6
Source File: Forms.spec.tsx    From ke with MIT License 5 votes vote down vote up
Input = forwardRef(
  (
    { value, onChange }: { value: string; onChange: (val: string) => void },
    ref: ForwardedRef<HTMLInputElement>
  ): JSX.Element => <input ref={ref} value={value} onChange={(event) => onChange(event.target.value)} />
)
Example #7
Source File: index.tsx    From ui with MIT License 5 votes vote down vote up
SheetWrap = forwardRef(
  (
    {
      data,
      children,
      setOptions,
      ...props
    }: {
      children: React.ReactNode;
      setOptions: (options: any) => void;
      data: SheetWrapData;
    } & SheetProps,
    ref: ForwardedRef<SheetWrapInstance>,
  ) => {
    const page = getCurrentPage();
    const sheetRef = useRef<SheetInstance>(null);
    const [promiseFn, setPromiseFn] = useState<any>({
      resolve: () => {},
      reject: () => {},
    });
    const [sheetProps, setSheetProps] = useState<Partial<SheetProps>>({});
    useEffect(() => {
      data[page] = {
        fn: ({ maskClosable, ...options }) =>
          new Promise((resolve, reject) => {
            setOptions(options);
            setSheetProps({ maskClosable });
            sheetRef.current?.setVisible(true);
            setPromiseFn({ reject, resolve });
          }),
        setVisible: sheetRef.current?.setVisible,
      };
    }, [data, page, setOptions]);
    useImperativeHandle(
      ref,
      () => ({ promiseRef: promiseFn, sheetRef: sheetRef.current }),
      [promiseFn],
    );
    return (
      <Sheet ref={sheetRef} {...props} {...sheetProps}>
        {children}
      </Sheet>
    );
  },
)
Example #8
Source File: CommandPaletteSVG.tsx    From TidGi-Desktop with Mozilla Public License 2.0 5 votes vote down vote up
CommandPaletteIcon = forwardRef((props, reference: ForwardedRef<HTMLDivElement>) => (
  <SVGContainer {...props} ref={reference}>
    <CommandPaletteSVG />
  </SVGContainer>
))
Example #9
Source File: SearchField.tsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
SearchField = forwardRef(function SearchField(
  {
    inputId,
    name,
    value,
    valueChanged,
    placeholder = 'Search',
    fieldSize = 'large',
    readOnly,
    fieldType = 'primary',
    className,
    autoFocus,
    type,
    disabled,
    rightButtonProps = { type: 'button' },
    'aria-describedby': describedBy,
    onBlur: externalOnBlur,
    onFocus: externalOnFocus,
    ...props
  }: SearchFieldProps,
  ref: ForwardedRef<HTMLDivElement>,
): ReactElement {
  const {
    inputRef,
    focused,
    hasInput,
    onFocus,
    onBlur,
    onInput,
    focusInput,
    setInput,
  } = useInputField(value, valueChanged);

  const onClearClick = (event: MouseEvent): void => {
    event.stopPropagation();
    setInput(null);
  };

  const isPrimary = fieldType === 'primary';
  const isSecondary = fieldType === 'secondary';
  const SearchIcon = focused ? MagnifyingFilledIcon : MagnifyingOutlineIcon;

  return (
    <BaseField
      {...props}
      className={classNames(
        fieldSize === 'medium' ? 'h-10 rounded-12' : 'h-12 rounded-14',
        className,
        { focused },
      )}
      onClick={focusInput}
      data-testid="searchField"
      ref={ref}
    >
      {isSecondary && hasInput ? (
        <Button
          type="button"
          className="mr-2 btn-tertiary"
          buttonSize="xsmall"
          title="Clear query"
          onClick={onClearClick}
          icon={
            <XIcon className="text-lg icon group-hover:text-theme-label-primary" />
          }
          disabled={!hasInput}
        />
      ) : (
        <SearchIcon
          className="mr-2 text-2xl icon"
          style={{
            color:
              focused || hasInput
                ? 'var(--theme-label-primary)'
                : 'var(--field-placeholder-color)',
          }}
        />
      )}
      <FieldInput
        placeholder={placeholder}
        name={name}
        id={inputId}
        ref={inputRef}
        onFocus={(event) => {
          onFocus();
          externalOnFocus?.(event);
        }}
        onBlur={(event) => {
          onBlur();
          externalOnBlur?.(event);
        }}
        onInput={onInput}
        autoFocus={autoFocus}
        type={type}
        aria-describedby={describedBy}
        autoComplete="off"
        className={classNames(
          'flex-1',
          getInputFontColor({ readOnly, disabled, hasInput, focused }),
        )}
        required
      />
      {((hasInput && isPrimary) || isSecondary) && (
        <Button
          {...rightButtonProps}
          className={isSecondary ? 'btn-primary' : 'btn-tertiary'}
          buttonSize={rightButtonProps.buttonSize || 'xsmall'}
          title={rightButtonProps.title || 'Clear query'}
          onClick={
            rightButtonProps.type !== 'submit'
              ? onClearClick
              : rightButtonProps.onClick
          }
          icon={<ButtonIcon isPrimary={isPrimary} />}
          disabled={rightButtonProps?.disabled || !hasInput}
        />
      )}
    </BaseField>
  );
})