sns 프로젝트

SearchBar 검색기능 만들기

우주속공간 2024. 1. 23. 00:01
📁 SearchBar  미리보기

 

 

 

SearchBar 기능 구현 과정을 간단하게 정리해보자면 다음과 같다.

 

프론트

  • Search bar 만들기
  1.  사용할때 실행할 백엔드 API prop으로 받아옴
  2.  search 버튼을 누르면 search 상태값 업데이트 . 전역적으로 관리
  3.  업데이트된 search 데이터를 가지고 prop으로 받은 API 실행

 

 

백엔드

  • search value값 param으로 받아서 데이터를 찾을때 search value값이 포함된 데이터만 가져오도록 설정

 

실제 구현한 코드


 

각 페이지에서 트윗 데이터를 가져오는 API가 다르기때문에 데이터를 가져오는 함수를 넘겨받아서 사용했다.

그리고 searchBar 디자인은 간단하게 tailwind에서 지원해주는 searchBar를 가져와 수정해서 사용했다.

const Searchbar = (onSearchbar: any) => {
  const [search, setSearch] = useState("");

  const dispatch = useDispatch();

  const onChange = (event: any) => {
    const { value } = event.target;
    setSearch(value);
  };

  const onSearch = (event: any) => {
    dispatch(changSearchState(search));
    event.preventDefault();
    
    // 각 페이지에서 트윗 데이터를 가져오는 API가 다르기때문에 데이터를 가져오는 함수를 넘겨받아서 사용.
    onSearchbar.onSearchbar();
  };

  return (
    <form className="flex justify-center w-full">
      <div className="relative w-3/5">
        <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
          <svg
            aria-hidden="true"
            className="w-5 h-5 text-gray-500 dark:text-gray-400"
            fill="currentColor"
            viewBox="0 0 20 20"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              fill-rule="evenodd"
              d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z"
              clip-rule="evenodd"
            ></path>
          </svg>
        </div>
        <input
          type="text"
          id="simple-search"
          className="bg-gray-50 border border-gray-300 outline-none text-gray-900 text-sm rounded-lg block w-full pl-10 p-2.5  dark:placeholder-gray-400 dark:text-white"
          placeholder="Search"
          required
          value={search}
          onChange={onChange}
        />
      </div>
      <button
        type="submit"
        onClick={onSearch}
        className="p-2.5 ml-2 text-sm font-medium text-white bg-blue-300 rounded-lg hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 dark:bg-blue-600"
      >
        <svg
          className="w-5 h-5"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
          ></path>
        </svg>
        <span className="sr-only">Search</span>
      </button>
    </form>
  );
};

 

https://flowbite.com/docs/forms/search-input/

 

Tailwind CSS Search Input - Flowbite

Use the search input component as a text field to allow users to enter search queries and receive relevant page results available in multiple styles and sizes

flowbite.com