条件絞り込み

1import React from 'react';
2import { searchClient } from '../algolia/client';
3import { InstantSearch } from 'react-instantsearch-dom';
4import CustomHits from '../components/custom-hits';
5import CustomRefinementList from '../components/custom-refinement-list';
6import { useRouter } from 'next/router';
7import { SearchState } from 'react-instantsearch-core';
8
9const SearchRefinementList = () => {
10  const router = useRouter();
11  const updateQueryParams = (state: SearchState) => {
12    router.replace(
13      {
14        query: {
15          id: router.query.id,
16          ...state.refinementList,
17        },
18      },
19      undefined,
20      {
21        shallow: true,
22      }
23    );
24  };
25
26  const getDefaultRefinement = () => {
27    const tags = router.query.tags;
28
29    if (!tags || !tags.length) {
30      return;
31    }
32
33    return typeof tags === 'string' ? [tags] : tags;
34  };
35
36  return (
37    <InstantSearch
38      onSearchStateChange={updateQueryParams}
39      searchClient={searchClient}
40      indexName="posts"
41    >
42      <div className="flex">
43        <div className="border-r w-40 mr-6">
44          <h2 className="mb-2">タグ</h2>
45          <CustomRefinementList
46            attribute="tags"
47            defaultRefinement={getDefaultRefinement()}
48          />
49        </div>
50        <div className="flex-1">
51          <CustomHits />
52        </div>
53      </div>
54    </InstantSearch>
55  );
56};
57
58export default SearchRefinementList;

解説

デフォルトでは選択した条件が一番上にソートされますがダッシュボードから並び順を指定することで条件の順序が固定されます。

使用ライブラリ

参考サイト