SearchForm.tsx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import React, {
  2. useCallback, useRef, useEffect, useMemo,
  3. } from 'react';
  4. import { GetInputProps } from '../interfaces/downshift';
  5. type Props = {
  6. searchKeyword: string,
  7. onChange?: (text: string) => void,
  8. onSubmit?: () => void,
  9. getInputProps: GetInputProps,
  10. }
  11. export const SearchForm = (props: Props): JSX.Element => {
  12. const {
  13. searchKeyword, onChange, onSubmit, getInputProps,
  14. } = props;
  15. const inputRef = useRef<HTMLInputElement>(null);
  16. const changeSearchTextHandler = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
  17. onChange?.(e.target.value);
  18. }, [onChange]);
  19. const submitHandler = useCallback((e: React.FormEvent<HTMLFormElement>) => {
  20. e.preventDefault();
  21. const isEmptyKeyword = searchKeyword.trim().length === 0;
  22. if (isEmptyKeyword) {
  23. return;
  24. }
  25. onSubmit?.();
  26. }, [searchKeyword, onSubmit]);
  27. const inputOptions = useMemo(() => {
  28. return getInputProps({
  29. type: 'search',
  30. placeholder: 'Search...',
  31. className: 'form-control',
  32. ref: inputRef,
  33. value: searchKeyword,
  34. onChange: changeSearchTextHandler,
  35. });
  36. }, [getInputProps, searchKeyword, changeSearchTextHandler]);
  37. useEffect(() => {
  38. if (inputRef.current != null) {
  39. inputRef.current.focus();
  40. }
  41. });
  42. return (
  43. <form className="w-100" onSubmit={submitHandler}>
  44. <input {...inputOptions} />
  45. </form>
  46. );
  47. };