All files / store/components/SearchInput SearchInput.tsx

100% Statements 11/11
100% Branches 6/6
100% Functions 3/3
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 46 47 48 49 50 51 52                2x 6x   6x 2x   2x 1x 1x 1x       6x                                   1x 1x                      
import { Button } from "@canonical/react-components";
import { RefObject } from "react";
import { useSearchParams } from "react-router-dom";
 
type Props = {
  searchRef: RefObject<HTMLInputElement>;
};
 
export const SearchInput = ({ searchRef }: Props) => {
  const [searchParams, setSearchParams] = useSearchParams();
 
  const onSearch = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
 
    if (searchRef?.current && searchRef.current.value) {
      searchParams.delete("page");
      searchParams.set("q", searchRef.current.value);
      setSearchParams(searchParams);
    }
  };
 
  return (
    <form className="p-search-box" onSubmit={onSearch}>
      <label className="u-off-screen" htmlFor="search">
        Search Charmhub
      </label>
      <input
        type="search"
        id="search"
        className="p-search-box__input"
        name="q"
        placeholder="Search Charmhub"
        defaultValue={searchParams.get("q") || ""}
        ref={searchRef}
      />
      <Button
        type="reset"
        className="p-search-box__reset"
        onClick={() => {
          searchParams.delete("q");
          setSearchParams(searchParams);
        }}
      >
        <i className="p-icon--close">Close</i>
      </Button>
      <Button type="submit" className="p-search-box__button">
        <i className="p-icon--search">Search</i>
      </Button>
    </form>
  );
};