Update search functionality - dynamic url update, auto focus

This commit is contained in:
Sat Naing
2022-09-29 11:29:37 +06:30
parent 18e920d0f7
commit 33bab9c489
+29 -1
View File
@@ -1,6 +1,6 @@
// import type React from "react"; // import type React from "react";
import Fuse from "fuse.js"; import Fuse from "fuse.js";
import { useEffect, useState } from "react"; import { useEffect, useRef, useState } from "react";
import Card from "@components/Card"; import Card from "@components/Card";
import slugify from "@utils/slugify"; import slugify from "@utils/slugify";
import type { Frontmatter } from "src/types"; import type { Frontmatter } from "src/types";
@@ -22,6 +22,7 @@ interface SearchResult {
} }
export default function SearchBar({ searchList }: Props) { export default function SearchBar({ searchList }: Props) {
const inputRef = useRef<HTMLInputElement>(null);
const [inputVal, setInputVal] = useState(""); const [inputVal, setInputVal] = useState("");
const [searchResults, setSearchResults] = useState<SearchResult[] | null>( const [searchResults, setSearchResults] = useState<SearchResult[] | null>(
null null
@@ -38,8 +39,33 @@ export default function SearchBar({ searchList }: Props) {
threshold: 0.5, threshold: 0.5,
}); });
useEffect(() => {
// if URL has search query,
// insert that search query in input field
const searchUrl = new URLSearchParams(window.location.search);
const searchStr = searchUrl.get("q");
if (searchStr) setInputVal(searchStr);
// put focus cursor at the end of the string
setTimeout(function () {
inputRef.current!.selectionStart = inputRef.current!.selectionEnd =
searchStr?.length || 0;
}, 50);
}, []);
useEffect(() => { useEffect(() => {
setSearchResults(fuse!.search!(inputVal!)); setSearchResults(fuse!.search!(inputVal!));
// Update search string in URL
if (inputVal.length > 0) {
const searchParams = new URLSearchParams(window.location.search);
searchParams.set("q", inputVal);
const newRelativePathQuery =
window.location.pathname + "?" + searchParams.toString();
history.pushState(null, "", newRelativePathQuery);
} else {
history.pushState(null, "", window.location.pathname);
}
}, [inputVal]); }, [inputVal]);
return ( return (
@@ -62,6 +88,8 @@ export default function SearchBar({ searchList }: Props) {
defaultValue={inputVal} defaultValue={inputVal}
onChange={handleChange} onChange={handleChange}
autoComplete="off" autoComplete="off"
autoFocus
ref={inputRef}
/> />
</label> </label>