All files / store/components/SearchInput SearchInput.tsx

47.05% Statements 8/17
66.66% Branches 4/6
50% Functions 3/6
47.05% Lines 8/17

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 53 54 55          1x 1x 1x     1x 1x     1x                 1x           1x                                                  
import { Button } from "@canonical/react-components";
import { useSearchParams } from "react-router-dom";
import { useEffect, useState } from "react";
 
function SearchInput() {
  const [searchParams, setSearchParams] = useSearchParams();
  const [searchTerm, setSearchTerm] = useState(
    () => searchParams.get("q") || ""
  );
 
  useEffect(() => {
    setSearchTerm(searchParams.get("q") || "");
  }, [searchParams]);
 
  const onSubmit = (event: React.FormEvent<HTMLFormElement>): void => {
    event.preventDefault();
    if (searchTerm) {
      searchParams.delete("page");
      searchParams.set("q", searchTerm);
      setSearchParams(searchParams);
    }
  };
 
  const onReset = (): void => {
    searchParams.delete("q");
    setSearchParams(searchParams);
    setSearchTerm("");
  };
 
  return (
    <form className="p-search-box" onSubmit={onSubmit}>
      <label className="u-off-screen" htmlFor="search">
        Search Rocks
      </label>
      <input
        type="search"
        id="search"
        className="p-search-box__input"
        name="q"
        placeholder="Search Rocks"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <Button type="reset" className="p-search-box__reset" onClick={onReset}>
        <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>
  );
}
 
export default SearchInput;