๐Ÿ“ฆ himself65 / npm-download-stat

๐Ÿ“„ search-bar.tsx ยท 45 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45"use client";

import { useRouter } from "next/navigation";
import { useCallback, useId } from "react";

export function SearchBar() {
  const idPrefix = useId();
  const inputId = `${idPrefix}-search`;

  const router = useRouter();

  const search = useCallback((formData: FormData) => {
    const searchQuery = formData.get(inputId);
    if (searchQuery && typeof searchQuery === 'string') {
      router.push(`/${encodeURIComponent(searchQuery)}`);
    }
  }, []);

  return (
    <>
      <div className="flex flex-col justify-center items-center w-full">
        <form
          className="flex flex-col justify-center items-center"
          action={search}
        >
          <div>
            <label className="sr-only" />
            <input
              className="w-full border border-gray-300 p-2 rounded-lg"
              placeholder="a npm package"
              name={inputId}
            />
          </div>
          <button
            className="bg-gray-800 text-white p-2 rounded-lg mt-2"
            type="submit"
          >
            Search
          </button>
        </form>
      </div>
    </>
  );
}