react#forwardRef TypeScript Examples

The following examples show how to use react#forwardRef. 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: classed.ts    From apps with GNU Affero General Public License v3.0 7 votes vote down vote up
function classed<T, P extends Record<string, unknown>>(
  type: ElementType,
  ...className: string[]
): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>> {
  return forwardRef<T, P>(function Classed(props, ref) {
    return React.createElement(type, {
      ...props,
      className: classNames(
        // eslint-disable-next-line react/prop-types
        props?.className,
        ...className,
      ),
      ref,
    });
  });
}
Example #2
Source File: SearchBar.tsx    From one-platform with MIT License 6 votes vote down vote up
SearchBar = forwardRef<HTMLInputElement, Props>(
  ({ onChange, className, ...props }, ref): JSX.Element => {
    return (
      <div className={css(styles['search-bar--container'], className)}>
        <span className={styles['search-bar--input-group']}>
          <input
            {...props}
            onChange={(e) => onChange(e.target.value)}
            ref={ref}
            className={styles['search-bar--input']}
          />
          <span className={styles['search-bar--input-icon-group']}>
            <svg width="24" height="24" fillRule="evenodd" clipRule="evenodd">
              <path
                d="M15.853 16.56c-1.683 1.517-3.911 2.44-6.353 2.44-5.243 0-9.5-4.257-9.5-9.5s4.257-9.5 9.5-9.5 9.5 4.257 9.5 9.5c0 2.442-.923 4.67-2.44 6.353l7.44 7.44-.707.707-7.44-7.44zm-6.353-15.56c4.691 0 8.5 3.809 8.5 8.5s-3.809 8.5-8.5 8.5-8.5-3.809-8.5-8.5 3.809-8.5 8.5-8.5z"
                stroke="white"
              />
            </svg>
          </span>
        </span>
      </div>
    );
  }
)
Example #3
Source File: Dialog.tsx    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
DialogBase = forwardRef<HTMLDivElement, DialogProps>(
  ({ onClose, color = 'normal', children, ...divProps }: DialogProps, ref) => {
    const ErrorBoundary = getErrorBoundary();

    return (
      <div {...divProps} ref={ref} data-color={color}>
        <div className="dialog-content">
          <ErrorBoundary>{children}</ErrorBoundary>
        </div>
        {onClose && (
          <svg
            className="dialog-close-button"
            viewBox="0 0 16 16"
            onClick={onClose}
          >
            <g transform="matrix(1,0,0,1,-953.896,-435.63)">
              <g transform="matrix(0.405863,0.405863,-0.354409,0.354409,674.668,-219.158)">
                <path d="M1152.39,529.839L1187.24,529.839" />
              </g>
              <g transform="matrix(-0.405863,0.405863,-0.354409,-0.354409,1624.24,156.402)">
                <path d="M1152.39,529.839L1187.24,529.839" />
              </g>
            </g>
          </svg>
        )}

        <ScrollLock />
      </div>
    );
  },
)
Example #4
Source File: Collapse.tsx    From next-saas-starter with MIT License 6 votes vote down vote up
Collapse = forwardRef<HTMLDivElement, PropsWithChildren<CollapseProps>>(
  (
    {
      isOpen,
      animateOpacity = true,
      onAnimationStart,
      onAnimationEnd,
      duration,
      easing = 'ease',
      startingHeight = 0,
      endingHeight = 'auto',
      ...rest
    },
    ref,
  ) => {
    return (
      <AnimateHeight
        duration={duration}
        easing={easing}
        animateOpacity={animateOpacity}
        height={isOpen ? endingHeight : startingHeight}
        applyInlineTransitions={false}
        {...{ onAnimationStart, onAnimationEnd }}
        style={{
          transition: 'height .3s ease,opacity .3s ease-in-out,transform .3s ease-in-out',
          backfaceVisibility: 'hidden',
        }}
      >
        <div ref={ref} {...rest} />
      </AnimateHeight>
    );
  },
)
Example #5
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 #6
Source File: index.tsx    From chartsy with GNU General Public License v3.0 6 votes vote down vote up
Home: React.FC = () => {
  const [showDrawer, setShowDrawer] = useState(false);
  const [searchType, setSearchType] = useState(SearchType.Music);

  const collageRef = createRef<HTMLDivElement>();
  const MyChart = forwardRef<HTMLDivElement>((_, ref) => <Chart searchType={searchType} collageRef={ref} />);
  const MyNav = forwardRef<HTMLDivElement>((_, ref) => <Nav collageRef={ref} setShowDrawer={setShowDrawer} />);

  return (
    <TitlesProvider>
      <ConfigProvider>
        <ImageGridProvider>
          <MyNav ref={collageRef} />
          <Sidebar.Pushable>
            <Sidebar as={Menu} animation="push" onHide={() => setShowDrawer(false)} vertical visible={showDrawer}>
              <ConfigMenu />
            </Sidebar>

            <Sidebar.Pusher>
              <Search searchType={searchType} setSearchType={setSearchType} />
              <div className="home" data-test="homeComponent">
                <MyChart ref={collageRef} />
              </div>
            </Sidebar.Pusher>
          </Sidebar.Pushable>
        </ImageGridProvider>
      </ConfigProvider>
    </TitlesProvider>
  );
}
Example #7
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 #8
Source File: index.tsx    From dnde with GNU General Public License v3.0 6 votes vote down vote up
wrapContext = forwardRef((props: EmailEditorProps, ref) => (
  <HtmlContextProvider>
    <CustomEditorProvider>
      <Ckeditor>
        <DNDContext>
          <EDContext>
            <Editor {...props} ref={ref} />
          </EDContext>
        </DNDContext>
      </Ckeditor>
    </CustomEditorProvider>
  </HtmlContextProvider>
))
Example #9
Source File: Button.tsx    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
PlainButton = forwardRef<HTMLButtonElement, ButtonProps>(
  function PlainButton(props, ref) {
    const { children, className, type = "button", ...buttonProps } = props;

    return (
      <button
        {...buttonProps}
        type={type}
        className={classNames("rounded", className)}
        ref={ref}
      >
        {children}
      </button>
    );
  }
)
Example #10
Source File: IconButton.tsx    From amazon-chime-live-events with Apache License 2.0 6 votes vote down vote up
IconButton: React.FC<Props> = forwardRef(
  (props: Props, ref?: React.Ref<HTMLButtonElement>) => {
    const {
      icon,
      active,
      pulse,
      className,
      isLoading,
      variant = 'default',
      ...rest
    } = props;

    return (
      <button
        className={cx(
          'button',
          `button--${variant}`,
          { active, pulse },
          className
        )}
        ref={ref}
        {...rest}
      >
        <i className={isLoading ? icons.SPINNER : icon} />
      </button>
    );
  }
)
Example #11
Source File: index.tsx    From amazon-chime-sdk-smart-video-sending-demo with Apache License 2.0 6 votes vote down vote up
Button = forwardRef((props: ButtonProps, ref: React.Ref<HTMLButtonElement>) => (
  <StyledButton
    {...props}
    className={props.className || ''}
    as={props.tag}
    ref={ref}
    aria-label={props.label}
    data-testid='button'
  >
    { props.icon &&
      <span className='icon' data-testid='button-icon'>
        {props.icon}
      </span>
    }
    <span className='label' data-testid='button-label'>{props.label}</span>
  </StyledButton>

))
Example #12
Source File: Table.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
tableIcons: Icons = {
  Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
  Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
  Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
  Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
  DetailPanel: forwardRef((props, ref) => (
    <ChevronRight {...props} ref={ref} />
  )),
  Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
  Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
  Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
  FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
  LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
  NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
  PreviousPage: forwardRef((props, ref) => (
    <ChevronLeft {...props} ref={ref} />
  )),
  ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
  Search: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
  SortArrow: forwardRef((props, ref) => <ArrowUpward {...props} ref={ref} />),
  ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
  ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />),
}
Example #13
Source File: index.tsx    From frontend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
Input = forwardRef<HTMLInputElement, InputProps>(({
  type = 'text',
  wrapperStyle,
  wrapperClass,
  prefix,
  suffix,
  placeholder,
  ...rest
}, ref) => {
  return (
    <div className={classnames('bgm-input__wrapper', wrapperClass)} style={wrapperStyle}>
      {prefix && prefix}
      <input type={type} className="bgm-input" placeholder={placeholder} ref={ref} {...rest} />
      {suffix && suffix}
    </div>
  )
})
Example #14
Source File: button.tsx    From basement-grotesque with SIL Open Font License 1.1 6 votes vote down vote up
Button = forwardRef(
  (
    { children, className, disabled, isLoading, variant, icon, ...props },
    ref
  ) => {
    return (
      <StyledButton
        {...props}
        className={clsx(className)}
        disabled={isLoading || disabled}
        ref={ref}
        underlined={variant === 'underlined'}
        hasIcon={!!icon}
      >
        {children} {icon && typeof icon !== 'boolean' ? icon : null}
      </StyledButton>
    )
  }
) as Polymorphic.ForwardRefComponent<'button', ButtonProps>
Example #15
Source File: CheckBox.tsx    From ke with MIT License 6 votes vote down vote up
CheckBox = forwardRef<HTMLInputElement, CheckBoxProps>((props, ref): JSX.Element => {
  const { value: inputValue, onChange, helpText, ...rest } = props
  const [value, setValue] = usePropState(inputValue)

  const handleChange = useCallback(
    (v: boolean): void => {
      setValue(v)
      onChange(v)
    },
    [setValue, onChange]
  )

  // Это обёртка
  /* eslint-disable react/jsx-props-no-spreading */
  return (
    <Box>
      <ChakraCheckBox
        verticalAlign="middle"
        isChecked={value}
        onChange={(e) => handleChange(e.target.checked)}
        ref={ref}
        {...rest}
      >
        {helpText || ''}
      </ChakraCheckBox>
    </Box>
  )
})
Example #16
Source File: EnumComponent.tsx    From brick-design with MIT License 6 votes vote down vote up
EnumComponent = forwardRef(function Component(
  props: EnumComponentPropsType,
  ref: any,
) {
  const { enumData, ...rest } = props;
  return (
    <Select
      ref={ref}
      style={{ width: '100%', height: 24 }}
      className={styles.select}
      showSearch
      allowClear
      {...rest}
    >
      {map(enumData, (item, index) => {
        let key = '',
          label = '';
        if (isObject(item)) {
          ({ key, label } = item);
        } else {
          key = label = item;
        }
        return (
          <Option value={key} key={index}>
            <Tooltip overlayStyle={{ zIndex: 1800 }} title={label}>
              {label}
            </Tooltip>
          </Option>
        );
      })}
    </Select>
  );
})
Example #17
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 #18
Source File: index.spec.tsx    From che-dashboard-next with Eclipse Public License 2.0 6 votes vote down vote up
jest.mock('../../../../components/DevfileEditor', () => {
  return forwardRef(function DummyEditor(...args: any[]): React.ReactElement {
    const { devfile, onChange } = args[0];
    const devfileStr = JSON.stringify(devfile);
    function onContentChange(event) {
      event.persist();
      const { value } = event.target;
      /* Expected an empty value and a valid JSON string */
      if (!value) {
        onChange(value, false);
      } else {
        onChange(JSON.parse(value), true);
      }
    }
    const input = (<input
      data-testid="dummy-editor"
      name="dummy-editor"
      type="text"
      onChange={onContentChange}
      value={devfileStr}
    />);
    return input;
  });
});
Example #19
Source File: Page.tsx    From dnd-kit with MIT License 6 votes vote down vote up
Page = forwardRef<HTMLLIElement, Props>(function Page(
  {id, index, active, clone, insertPosition, layout, onRemove, style, ...props},
  ref
) {
  return (
    <li
      className={classNames(
        styles.Wrapper,
        active && styles.active,
        clone && styles.clone,
        insertPosition === Position.Before && styles.insertBefore,
        insertPosition === Position.After && styles.insertAfter,
        layout === Layout.Vertical && styles.vertical
      )}
      style={style}
      ref={ref}
    >
      <button className={styles.Page} data-id={id.toString()} {...props} />
      {!active && onRemove ? (
        <button className={styles.Remove} onClick={onRemove}>
          {removeIcon}
        </button>
      ) : null}
      {index != null ? (
        <span className={styles.PageNumber}>{index}</span>
      ) : null}
    </li>
  );
})
Example #20
Source File: refUtil.tsx    From clearflask with Apache License 2.0 6 votes vote down vote up
withForwardedRef = Comp => {
  const handle = (props, ref) => (
    <Comp {...props} forwardedRef={ref} />
  );
  const name = Comp.displayName || Comp.name;
  handle.displayName = `withForwardedRef(${name})`;

  return forwardRef(handle);
}
Example #21
Source File: DatePicker.tsx    From back-home-safe with GNU General Public License v3.0 6 votes vote down vote up
DatePicker = forwardRef((props: any, ref: any) => {
  const [pickerInstance, setPickerInstance] = useState<Picker | null>(null);

  // mount effect wont work on model, need to call this after onAfterOpen event
  useImperativeHandle(ref, () => ({
    init: () => {
      const ele = document.querySelector(
        ".js-inline-picker"
      ) as HTMLElement | null;
      if (!ele) return;
      setPickerInstance(
        new Picker(ele, {
          inline: true,
          rows: 2,
        })
      );
    },
    getValue: () => {
      if (!pickerInstance) return "";
      return pickerInstance.getDate();
    },
  }));

  return (
    <Wrapper>
      <div className="js-inline-picker" />
    </Wrapper>
  );
})
Example #22
Source File: DropdownMenu.tsx    From raspiblitz-web with MIT License 6 votes vote down vote up
DropdownMenu = forwardRef<HTMLDivElement>((_, ref) => {
  const { t } = useTranslation();
  const { unit, darkMode, logout, toggleDarkMode, toggleUnit } =
    useContext(AppContext);
  const unitActive = unit === Unit.SAT;

  const logoutHandler = () => {
    logout();
  };

  return (
    <div
      ref={ref}
      className="absolute top-14 right-5 z-10 flex w-56 rounded-lg border border-black bg-white dark:border-gray-300 dark:bg-gray-800"
    >
      <div className="flex w-full flex-col items-center justify-center text-center">
        <div className="w-full py-4">
          <Toggle
            toggleText={t("navigation.display_sats")}
            active={unitActive}
            toggleFn={toggleUnit}
          />
        </div>
        <div className="w-full py-4">
          <Toggle
            toggleText={t("navigation.dark_mode")}
            active={darkMode}
            toggleFn={toggleDarkMode}
          />
        </div>
        <button className="bd-button mt-3 w-full py-2" onClick={logoutHandler}>
          <LogoutIcon className="inline-block h-5 w-5" /> &nbsp;
          {t("navigation.logout")}
        </button>
      </div>
    </div>
  );
})
Example #23
Source File: AdList.tsx    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
AdList = forwardRef(function AdList(
  { ad, onLinkClick, postHeadingFont, ...props }: AdCardProps,
  ref: Ref<HTMLElement>,
): ReactElement {
  return (
    <ListCard {...props} ref={ref}>
      <AdLink ad={ad} onLinkClick={onLinkClick} />
      <ListCardAside />
      <ListCardDivider />
      <ListCardMain>
        <ListCardTitle className={classNames('line-clamp-4', postHeadingFont)}>
          {ad.description}
        </ListCardTitle>
        <AdAttribution ad={ad} className="mt-2" />
      </ListCardMain>
    </ListCard>
  );
})
Example #24
Source File: Toolbar.tsx    From crypto-fees with MIT License 6 votes vote down vote up
DateButton = forwardRef<
  HTMLButtonElement,
  { onClick?: any; value?: string; loading?: boolean }
>(({ onClick, value, loading }, ref) => {
  const { t } = useTranslation();
  return (
    <Button ref={ref} onClick={onClick} Icon={Calendar}>
      {loading ? <div className="loader" /> : value || t('Yesterday')}

      <style jsx>{`
        .loader {
          display: inline-block;
          width: 20px;
          height: 20px;
          margin: 0 10px;
        }
        .loader:after {
          content: ' ';
          display: block;
          width: 16px;
          height: 16px;
          border-radius: 50%;
          border: 2px solid #333;
          border-color: #333 transparent #333 transparent;
          animation: lds-dual-ring 1.2s linear infinite;
        }
        @keyframes lds-dual-ring {
          0% {
            transform: rotate(0deg);
          }
          100% {
            transform: rotate(360deg);
          }
        }
      `}</style>
    </Button>
  );
})
Example #25
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 #26
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 #27
Source File: AbstractFormControl.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
AbstractFormControl = forwardRef<
  HTMLElement, // antd 3.x 的自定义表单控件需要支持 ref,升到 4.x 以后可移除
  AbstractFormControlProps
>(function AbstractFormControl(props, ref): React.ReactElement {
  const {
    control,
    value,
    controlValue,
    onChange,
    onControlValueChange,
  } = props;
  const valueRef = useRef();

  useEffect(() => {
    if (controlValue !== valueRef.current) {
      valueRef.current = controlValue;

      onChange?.(controlValue);
    }
  }, [controlValue]);

  useEffect(() => {
    if (value !== valueRef.current) {
      valueRef.current = value;

      onControlValueChange?.(value);
    }
  }, [value]);

  return (
    <>
      <slot id="controlSlot" name="control" ref={ref} />
      {control && <BrickAsComponent useBrick={control.useBrick} />}
    </>
  );
})
Example #28
Source File: button.tsx    From next-eui-starter with Apache License 2.0 6 votes vote down vote up
NextEuiButton = forwardRef<
  HTMLAnchorElement | HTMLButtonElement,
  EuiButtonProps
>((props, ref) => {
  return (
    // @ts-ignore EuiButton's ref is an HTMLButtonElement or an
    // HTMLAnchorElement, depending on whether `href` prop is passed
    <EuiButton {...props} buttonRef={ref}>
      {props.children}
    </EuiButton>
  );
})
Example #29
Source File: LibraryMenu.tsx    From excalidraw with MIT License 6 votes vote down vote up
LibraryMenuWrapper = forwardRef<
  HTMLDivElement,
  { children: React.ReactNode }
>(({ children }, ref) => {
  return (
    <Island padding={1} ref={ref} className="layer-ui__library">
      {children}
    </Island>
  );
})