react#createRef TypeScript Examples

The following examples show how to use react#createRef. 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: HamburgerMenu.tsx    From pola-web with MIT License 6 votes vote down vote up
HamburgerMenu: React.FC<IHamburgerMenu> = ({ expanded, children, onExpand }) => {
  const itemsRef = createRef<HTMLDivElement>();

  const handleOpen = (e: React.MouseEvent<SVGSVGElement, MouseEvent>) => {
    onExpand(!expanded);
    const items = itemsRef.current;
    items?.classList.toggle('open');
  };

  return (
    <HamburgerLayout className="hamburger-menu">
      <Navbar>
        <Link to={urls.pola.home()}>
          <img width="auto" height="100%" src={LogoColor} />
        </Link>
        <FontAwesomeIcon icon={faBars} onClick={handleOpen} className="menu-icon" size="2x" />
      </Navbar>
      <Items ref={itemsRef} className={classNames('nav-items')}>
        {children}
      </Items>
    </HamburgerLayout>
  );
}
Example #2
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 #3
Source File: index.tsx    From react-native-actions-sheet with MIT License 6 votes vote down vote up
constructor(props: ActionSheetProps) {
    super(props);
    this.state = {
      modalVisible: false,
      scrollable: false,
      layoutHasCalled: false,
      keyboard: false,
      deviceHeight:
        calculatedDeviceHeight ||
        getDeviceHeight(this.props.statusBarTranslucent),
      deviceWidth: Dimensions.get("window").width,
      portrait: true,
      safeAreaInnerHeight,
      paddingTop: safeAreaPaddingTop,
      keyboardPadding: 0,
    };

    this.scrollViewRef = createRef();
    this.safeAreaViewRef = createRef();

    this.currentOffsetFromBottom = this.props.initialOffsetFromBottom ?? 1;
    this.indicatorTranslateY = new Animated.Value(-this.state.paddingTop | 0);
  }
Example #4
Source File: index.tsx    From amazon-chime-sdk-smart-video-sending-demo with Apache License 2.0 6 votes vote down vote up
VideoGrid: React.FC<VideoGridProps> = ({ size, children, ...props }) => {
  const gridEl = createRef<HTMLDivElement>();
  const ratio = useElementAspectRatio(gridEl);

  return (
    <StyledGrid
      ref={gridEl}
      {...props}
      size={size}
      ratio={ratio}
      data-testid='video-grid'
    >
      {children}
    </StyledGrid>
  );
}
Example #5
Source File: useContainerHandler.ts    From react-design-editor with MIT License 6 votes vote down vote up
function useContainerHandler() {
  const containerRef = createRef<HTMLDivElement>()
  const { canvas } = useCanvasContext()
  const updateCanvasSize = useCallback(
    (x, y) => {
      if (canvas) {
        canvas.setHeight(y).setWidth(x)
        canvas.renderAll()
        // @ts-ignore
        const workarea = canvas.getObjects().find(obj => obj.id === 'workarea')
        if (workarea) {
          workarea.center()
        }
      }
    },
    [canvas]
  )
  useEffect(() => {
    const containerWidth = containerRef.current.clientWidth
    const containerHeight = containerRef.current.clientHeight
    updateCanvasSize(containerWidth, containerHeight)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [canvas])

  return containerRef
}
Example #6
Source File: page.tsx    From website with Apache License 2.0 6 votes vote down vote up
constructor(props: unknown) {
    super(props);
    this.fetchDataAndRender = this.fetchDataAndRender.bind(this);
    this.state = {
      placeName: {},
      statVarInfo: {},
      showSvHierarchyModal: false,
    };
    // Set up refs and callbacks for sv widget modal. Widget is tied to the LHS
    // menu but reattached to the modal when it is opened on small screens.
    this.svHierarchyModalRef = createRef<HTMLDivElement>();
    this.svHierarchyContainerRef = createRef<HTMLDivElement>();
    this.onSvHierarchyModalClosed = this.onSvHierarchyModalClosed.bind(this);
    this.onSvHierarchyModalOpened = this.onSvHierarchyModalOpened.bind(this);
    this.toggleSvHierarchyModal = this.toggleSvHierarchyModal.bind(this);
  }
Example #7
Source File: MultipleFilesForm.spec.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
describe("MultipleFilesForm", () => {
  it("should work", async () => {
    render(<MultipleFilesForm fieldList={[{ name: "file", type: "file" }]} />);

    expect(screen.getByText("upload")).toBeInTheDocument();
  });

  it("should work with files array", async () => {
    const mockFinishFn = jest.fn();
    const ref = createRef();
    render(
      <MultipleFilesForm
        fieldList={[{ name: "file", type: "file[]" }]}
        onFinish={mockFinishFn}
        ref={ref}
      />
    );
    fireEvent.submit(screen.getByTestId("files-form"));
    await (global as any).flushPromises();

    expect(mockFinishFn).toHaveBeenCalled();
  });
});
Example #8
Source File: index.tsx    From react-custom-roulette with MIT License 6 votes vote down vote up
WheelCanvas = ({
  width,
  height,
  data,
  outerBorderColor,
  outerBorderWidth,
  innerRadius,
  innerBorderColor,
  innerBorderWidth,
  radiusLineColor,
  radiusLineWidth,
  fontSize,
  perpendicularText,
  textDistance,
}: WheelCanvasProps): JSX.Element => {
  const canvasRef = createRef<HTMLCanvasElement>();
  const drawWheelProps = {
    outerBorderColor,
    outerBorderWidth,
    innerRadius,
    innerBorderColor,
    innerBorderWidth,
    radiusLineColor,
    radiusLineWidth,
    fontSize,
    perpendicularText,
    textDistance,
  };

  useEffect(() => {
    drawWheel(canvasRef, data, drawWheelProps);
  }, [canvasRef, data, drawWheelProps]);

  return <WheelCanvasStyle ref={canvasRef} width={width} height={height} />;
}
Example #9
Source File: index.tsx    From selftrace with MIT License 6 votes vote down vote up
constructor(props: TextInputProps) {
    super(props);
    this.isFocused = new Animated.Value(0); // 0: !focused, 1: focused
    this.labelColor = this.isFocused.interpolate({
      inputRange: [0, 1],
      outputRange: [Colors.INACTIVE_TEXT.toString(), Colors.BLUE.toString()],
    });
    this.borderBottomColor = this.isFocused.interpolate({
      inputRange: [0, 1],
      outputRange: [Colors.BORDER.toString(), Colors.BLUE.toString()],
    });
    this.textInputRef = createRef();
  }
Example #10
Source File: renderHook.tsx    From foca with MIT License 6 votes vote down vote up
export function renderHook<Result, Props>(
  renderCallback: (initialProps?: Props) => Result,
  options: RenderHookOptions<Props> = {},
): RenderHookResult<Result, Props> {
  const { initialProps, wrapper } = options;
  const result = createRef<Result>();

  const TestComponent: FC<{ renderCallbackProps?: Props }> = (props) => {
    const pendingResult = renderCallback(props.renderCallbackProps);

    useEffect(() => {
      // @ts-expect-error
      result.current = pendingResult;
    });

    return null;
  };

  const { rerender: baseRerender, unmount } = render(
    <TestComponent renderCallbackProps={initialProps} />,
    { wrapper },
  );

  function rerender(rerenderCallbackProps?: Props) {
    return baseRerender(
      <TestComponent renderCallbackProps={rerenderCallbackProps} />,
    );
  }

  return {
    // @ts-expect-error
    result,
    rerender,
    unmount,
  };
}
Example #11
Source File: index.tsx    From gio-design with Apache License 2.0 6 votes vote down vote up
useModal: IUseModal = () => {
  const [modalElements, patchModalElements] = usePatchElement();

  const getHookCalloutFnc = (config: IModalStaticFuncConfig) => {
    modalId += 1;

    const hookModalRef = createRef<THookModalRef>();

    let handleClose: () => void;
    const modal = (
      <HookModal key={`hook-modal-${modalId}`} ref={hookModalRef} config={config} afterClose={() => handleClose()} />
    );
    handleClose = patchModalElements(modal);

    return {
      destroy: () => {
        hookModalRef.current?.destroy();
      },
      update: (newConfig: IModalStaticFuncConfig) => {
        hookModalRef.current?.update(newConfig);
      },
    };
  };

  return [
    {
      open: getHookCalloutFnc,
    },
    <>{modalElements}</>,
  ];
}
Example #12
Source File: use-merged-ref.test.tsx    From mantine with MIT License 6 votes vote down vote up
describe('@mantine/hook/use-merged-ref', () => {
  it('assigns refs to all given arguments', () => {
    const objectRef = createRef<HTMLButtonElement>();
    let fnRefValue: HTMLButtonElement = null;
    const fnRef = (node: HTMLButtonElement) => {
      fnRefValue = node;
    };

    render(<TestComponent refs={[objectRef, fnRef]} />);
    expect(fnRefValue instanceof HTMLButtonElement).toBe(true);
    expect(objectRef.current instanceof HTMLButtonElement).toBe(true);
  });
});
Example #13
Source File: HoverOnAvatar.tsx    From next-cms-ghost with MIT License 6 votes vote down vote up
constructor(props: HoverOnAvatarProps) {
    super(props)
    this.anchorRef = createRef<HTMLLIElement>()
    this.activeClass = this.props.activeClass
    this.hoverTimeout = undefined
    this.state = {
      currentClass: ''
    }
  }
Example #14
Source File: common.tsx    From remote-office-hours-queue with Apache License 2.0 6 votes vote down vote up
CopyField: React.FC<CopyFieldProps> = (props) => {
    const [copied, setCopied] = useState(false);
    const inputRef = createRef<HTMLInputElement>();
    const buttonRef = createRef<HTMLButtonElement>();
    const copy = (focusButton?: boolean) => {
        inputRef.current!.select();
        document.execCommand("copy");
        if (focusButton) buttonRef.current!.focus();
        setCopied(true);
        setTimeout(() => setCopied(false), 3000);
    }
    const buttonInner = copied
        ? <span><FontAwesomeIcon icon={faClipboardCheck} /> Copied!</span>
        : <span><FontAwesomeIcon icon={faClipboard} /> Copy</span>
    const copiedSrAlert = copied
        && <span className="sr-only" role="alert" aria-live="polite">Copied</span>
    return (
        <>
            <div className="input-group">
                <input readOnly id={props.id} ref={inputRef} onClick={() => copy()} value={props.text} type="text" className="form-control" />
                <div className="input-group-append">
                    <button type="button" ref={buttonRef} onClick={() => copy(true)} className="btn btn-secondary">
                        {buttonInner}
                    </button>
                </div>
            </div>
            {copiedSrAlert}
        </>
    );
}
Example #15
Source File: useForkRef.test.ts    From use-platform with MIT License 6 votes vote down vote up
describe('useForkRef', () => {
  test('should copy value for each ref objects', () => {
    const refA = createRef()
    const refB = createRef()

    const setter = renderForkRefHook(refA, refB)
    setter?.('value' as any)

    expect(refA.current).toBe('value')
    expect(refB.current).toBe('value')
  })

  test('should copy value for each ref callbacks', () => {
    const refs = { a: null, b: null }
    const refA = (value: any) => {
      refs.a = value
    }
    const refB = (value: any) => {
      refs.b = value
    }

    const setter = renderForkRefHook(refA, refB)
    setter?.('value' as any)

    expect(refs.a).toBe('value')
    expect(refs.b).toBe('value')
  })
})
Example #16
Source File: useGetRefForId.ts    From calories-in with MIT License 6 votes vote down vote up
function useGetRefForId<T extends HTMLElement = HTMLElement>() {
  const cacheRef = useRef<RefsCache<T>>({})

  const getRef = useCallback((id: number | string) => {
    if (!cacheRef.current[id]) {
      cacheRef.current[id] = createRef()
    }

    return cacheRef.current[id]
  }, [])

  return getRef
}
Example #17
Source File: Chart.tsx    From AIPerf with MIT License 5 votes vote down vote up
container = createRef<HTMLDivElement>();
Example #18
Source File: ANCPriceChart.tsx    From anchor-web-app with Apache License 2.0 5 votes vote down vote up
private canvasRef = createRef<HTMLCanvasElement>();
Example #19
Source File: InteractiveToolPanel.tsx    From kliveide with MIT License 5 votes vote down vote up
private _listHost = createRef<HTMLDivElement>();
Example #20
Source File: AvalonScrollbars.tsx    From avalon.ist with MIT License 5 votes vote down vote up
scrollbars = createRef<Scrollbars>();
Example #21
Source File: single-code-input.tsx    From protect-scotland with Apache License 2.0 5 votes vote down vote up
SingleCodeInput: React.FC<SingleCodeInputProps> = ({
  style,
  disabled = false,
  autoFocus = false,
  onChange,
  error,
  count,
  accessibilityHint,
  accessibilityLabel
}) => {
  const [value, setValue] = useState<string>('');
  const inputRef = createRef<TextInput>();
  const fontScale = PixelRatio.getFontScale();

  useEffect(() => {
    const isScreenReaderEnabled = (async function () {
      await AccessibilityInfo.isScreenReaderEnabled();
    })();
    if (autoFocus && !isScreenReaderEnabled) {
      inputRef.current?.focus();
    }
  }, [inputRef, autoFocus]);

  const onChangeTextHandler = (v: string) => {
    const validatedValue = v.replace(/[^a-zA-Z0-9]/g, '');
    setValue(validatedValue);

    if (!validatedValue) {
      return;
    }

    if (onChange) {
      onChange(validatedValue);
    }
  };

  const onFocusHandler = () => {
    if (error) {
      inputRef.current?.clear();
      inputRef.current?.focus();
      if (onChange) {
        onChange(value);
      }
    }
  };

  return (
    <View style={[styles.container, style]}>
      <TextInput
        ref={inputRef}
        selectTextOnFocus
        autoCapitalize="characters"
        style={[
          styles.input,
          {height: 60 * fontScale},
          error ? styles.errorBlock : styles.block
        ]}
        maxLength={count}
        keyboardType="default"
        returnKeyType="done"
        editable={!disabled}
        value={value}
        placeholder="——————"
        onFocus={onFocusHandler}
        onChangeText={onChangeTextHandler}
        accessibilityLabel={accessibilityLabel}
        accessibilityHint={accessibilityHint}
      />
    </View>
  );
}
Example #22
Source File: DatePicker.tsx    From symphony-ui-toolkit with Apache License 2.0 5 votes vote down vote up
constructor(props) {
    super(props);

    const { date, format, initialMonth, locale } = props;

    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const getLocale: Locale = require(`date-fns/locale/${
      locale || 'en-US'
    }/index.js`);

    this.state = {
      navigationDate: initialMonth || this.computeDate(date) || new Date(),
      locale: getLocale,
      inputValue: this.computeDate(date)
        ? formatDate(date, format, { locale: getLocale })
        : null,
      showPicker: false,
      refIcon: createRef(),
      refContainer: null,
      popperElement: null,
      referenceElement: null,
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleDayClick = this.handleDayClick.bind(this);
    this.handleKeyDownIcon = this.handleKeyDownIcon.bind(this);
    this.handleKeyDownInput = this.handleKeyDownInput.bind(this);
    this.handleOnClose = this.handleOnClose.bind(this);

    this.handleClickOutside = this.handleClickOutside.bind(this);

    this.setRefContainer = this.setRefContainer.bind(this);
    this.setPopperElement = this.setPopperElement.bind(this);
    this.setReferenceElement = this.setReferenceElement.bind(this);

    this.mountDayPickerInstance = this.mountDayPickerInstance.bind(this);
    this.unmountDayPickerInstance = this.unmountDayPickerInstance.bind(this);

    this.handleScrollParent = this.handleScrollParent.bind(this);
    this.handleKeydownScrollParent = this.handleKeydownScrollParent.bind(this);
  }
Example #23
Source File: MediaPlayer.tsx    From lainTSX with GNU General Public License v3.0 5 votes vote down vote up
MediaPlayer = () => {
  const setPercentageElapsed = useStore((state) => state.setPercentageElapsed);

  // use it as a guard to avoid multiple set states inside updateTime
  const lastSetPercentageRef = useRef<undefined | number>(undefined);
  const language = useStore((state) => state.language);

  const requestRef = useRef();
  const videoRef = createRef<HTMLVideoElement>();
  const trackRef = createRef<HTMLTrackElement>();
  const subtitleRef = createRef<HTMLParagraphElement>();

  useEffect(() => {
    const handleCueChange = (e: any) => {
      const { track } = e.target;
      const { activeCues } = track;
      const text = [...activeCues].map(
        (cue) => cue.getCueAsHTML().textContent
      )[0];
      if (subtitleRef.current && videoRef.current) {
        if (!text || videoRef.current.currentTime === 0)
          subtitleRef.current.textContent = text;
        else subtitleRef.current.textContent = text;
      }
    };

    if (trackRef.current) {
      trackRef.current.addEventListener("cuechange", handleCueChange);
    }
  }, [subtitleRef, trackRef, videoRef]);

  const updateTime = useCallback(() => {
    (requestRef.current as any) = requestAnimationFrame(updateTime);
    if (videoRef.current) {
      const timeElapsed = videoRef.current.currentTime;
      const duration = videoRef.current.duration;
      const percentageElapsed = Math.floor((timeElapsed / duration) * 100);

      if (
        percentageElapsed % 5 === 0 &&
        lastSetPercentageRef.current !== percentageElapsed
      ) {
        setPercentageElapsed(percentageElapsed);
        lastSetPercentageRef.current = percentageElapsed;

        if (subtitleRef.current) {
          if (percentageElapsed === 0) {
            subtitleRef.current.style.visibility = "visible";
          } else if (percentageElapsed === 100) {
            subtitleRef.current.style.visibility = "hidden";
          }
        }
      }
    }
  }, [setPercentageElapsed, videoRef, subtitleRef]);

  useEffect(() => {
    (requestRef.current as any) = requestAnimationFrame(updateTime);
    const curr = requestRef.current;
    return () => {
      cancelAnimationFrame(curr as any);
      setPercentageElapsed(0);
    };
  }, [setPercentageElapsed, updateTime]);

  return (
    <>
      <video id="media" ref={videoRef} disablePictureInPicture>
        <track id={"track"} ref={trackRef} kind="metadata" default />
      </video>
      <div id={"subtitle-container"}>
        <p
          ref={subtitleRef}
          id={"subtitle"}
          style={language === "ko" ? { fontFamily: "sans-serif", wordBreak: "keep-all" } : {}}
        />
      </div>
    </>
  );
}
Example #24
Source File: index.tsx    From ChatUI with MIT License 5 votes vote down vote up
wrapperRef = createRef<HTMLDivElement>();
Example #25
Source File: Search.tsx    From checklist with MIT License 5 votes vote down vote up
Search: FC<Props> = ({ id, className }) => {
  const ref = createRef<HTMLDivElement>();

  const [query, setQuery] = useState('');
  const [focus, setFocus] = useState(false);

  useClickOutside(ref, () => {
    setFocus(false);
  });

  const handleSearchStateChange = ({ query: nextQuery }: { query: string }) => {
    setQuery(nextQuery);
  };

  const handleInputFocus = () => {
    setFocus(true);
  };

  const handleHitClick = () => {
    setFocus(false);
  };

  return (
    <InstantSearch
      searchClient={searchClient}
      indexName={indexName}
      onSearchStateChange={handleSearchStateChange}
    >
      <div className={cx('c-search', className)} ref={ref}>
        <Configure hitsPerPage={3} />
        <SearchInput onFocus={handleInputFocus} id={id} />
        {query && query.trim().length > 0 && focus && (
          <Results>
            <Hits onClick={handleHitClick} />
            <div className="c-search__powered-by">
              <a href="https://www.algolia.com" target="_blank" rel="noopener noreferrer">
                <img src={algolia} alt="Search by Algolia" width={112} height={16} />
              </a>
            </div>
          </Results>
        )}
      </div>
    </InstantSearch>
  );
}
Example #26
Source File: RemoteVideo.tsx    From amazon-chime-live-events with Apache License 2.0 5 votes vote down vote up
export default function RemoteVideo(props: Props) {
  const {
    isLive = false,
    enabled,
    className,
    videoElementRef,
    name = '',
    tileId,
    fullScreenVideo,
    bindVideoElement,
    unbindVideoElement,
    nameplatePosition = 'bottom',
  } = props;
  const containerRef = createRef<HTMLDivElement>();
  const videoRef = React.createRef<HTMLVideoElement>();
  const fontSize = useDynamicFontSize(containerRef);

  useEffect(() => {
    bindVideoElement && bindVideoElement(videoRef.current);
    return unbindVideoElement;
  }, [tileId]);

  return (
    <div
      ref={containerRef}
      className={cx('remoteVideo', className, {
        enabled,
        fullScreenVideo,
      })}
    >
      <video muted ref={videoElementRef || videoRef} className={styles.video} />
      {name && (
        <div
          style={{ fontSize }}
          className={cx('nameplate', `nameplate--${nameplatePosition}`)}
        >
          {name}
        </div>
      )}
      {isLive && <LiveIndicator />}
    </div>
  );
}
Example #27
Source File: Standard.test.tsx    From ke with MIT License 5 votes vote down vote up
describe.each([
  ['input', HTMLInputElement, Input],
  ['textarea', HTMLTextAreaElement, Textarea],
  ['select', HTMLSelectElement, Select],
])('Adapter for "%s"', (name, Element, Adapter) => {
  test(`Adapter includes only "${name}" element`, () => {
    fc.assert(
      fc.property(valueArbitrary, onChangeArbitrary, (value, onChange) => {
        const component = mount(<Adapter value={value} onChange={onChange} />)

        expect(component.children().length).toBe(1)
        expect(component.children().first().instance()).toBeInstanceOf(Element)
      })
    )
  })

  test(`Adapter forward "${name}" ref`, () => {
    fc.assert(
      fc.property(valueArbitrary, onChangeArbitrary, (value, onChange) => {
        const ref = createRef<InstanceType<typeof Element>>()
        // Don't know how to define relation between Adapter and Element, but this is correct
        // @ts-ignore
        const component = mount(<Adapter ref={ref} value={value} onChange={onChange} />)

        expect(ref.current).toBeInstanceOf(Element)
        expect(ref.current).toBe(component.children().first().instance())
      })
    )
  })

  test(`Adapter forward "${name}" changes value`, () => {
    fc.assert(
      fc.property(changesTupleArbitrary, ([value, changes]) => {
        const mockOnChange = jest.fn()
        const component = mount(<Adapter value={value} onChange={mockOnChange} />)
        const input = component.find(name)

        changes.forEach((changedValue) =>
          input.simulate('change', {
            target: {
              value: changedValue,
            },
          })
        )

        expect(mockOnChange.mock.calls).toEqual(changes.map((changedValue) => [changedValue]))
      })
    )
  })

  test(`Adapter inner "${name}" got props.value`, () => {
    fc.assert(
      fc.property(valueArbitrary, onChangeArbitrary, (value, onChange) => {
        const component = mount(<Adapter value={value} onChange={onChange} />)

        expect(component.find(name).prop('value')).toBe(value)
      })
    )
  })
})
Example #28
Source File: AdvancedVideo.tsx    From frontend-frameworks with MIT License 5 votes vote down vote up
constructor(props: VideoProps) {
    super(props);
    this.videoRef = createRef();
    this.attachRef = this.attachRef.bind(this);
  }
Example #29
Source File: InputFile.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function InputFile ({ accept, className = '', clearContent, help, isDisabled, isError = false, isFull, label, onChange, placeholder, withEllipsis, withLabel }: InputFileProps): React.ReactElement<InputFileProps> {
  const { t } = useTranslation();
  const dropRef = createRef<DropzoneRef>();
  const [file, setFile] = useState<FileState | undefined>();

  const _onDrop = useCallback(
    (files: File[]): void => {
      files.forEach((file): void => {
        const reader = new FileReader();

        reader.onabort = NOOP;
        reader.onerror = NOOP;

        reader.onload = ({ target }: ProgressEvent<FileReader>): void => {
          if (target && target.result) {
            const name = file.name;
            const data = convertResult(target.result as ArrayBuffer);

            onChange && onChange(data, name);
            dropRef && setFile({
              name,
              size: data.length
            });
          }
        };

        reader.readAsArrayBuffer(file);
      });
    },
    [dropRef, onChange]
  );

  const dropZone = (
    <Dropzone
      accept={accept}
      disabled={isDisabled}
      multiple={false}
      onDrop={_onDrop}
      ref={dropRef}
    >
      {({ getInputProps, getRootProps }): JSX.Element => (
        <div {...getRootProps({ className: `ui--InputFile${isError ? ' error' : ''} ${className}` })} >
          <input {...getInputProps()} />
          <em className='label' >
            {
              !file || clearContent
                ? placeholder || t<string>('click to select or drag and drop the file here')
                : placeholder || t<string>('{{name}} ({{size}} bytes)', {
                  replace: {
                    name: file.name,
                    size: formatNumber(file.size)
                  }
                })
            }
          </em>
        </div>
      )}
    </Dropzone>
  );

  return label
    ? (
      <Labelled
        help={help}
        isFull={isFull}
        label={label}
        withEllipsis={withEllipsis}
        withLabel={withLabel}
      >
        {dropZone}
      </Labelled>
    )
    : dropZone;
}