Latest

useSortBy

Purpose

The useSortBy hook exposes methods and data for sorting results, internally it is used by the SortBy component.

Usage

The sortOptions field is an array of all available sort options.

The sortOption field is the currently selected sort option, by default this is the first sort option.

The setSortOption method can be used to change the sort option, you must provide the handle value of one of the sort options.

import React from "react";
import { useSortBy } from "@usereactify/search";

export const ExampleHookUseSortBy: React.FC = () => {
  const sortByHook = useSortBy();

  const handleSelectChange = React.useCallback((event: React.ChangeEvent<HTMLSelectElement>) => {
    sortByHook.setSortOption(event.target.value);
  }, [sortByHook.setSortOption]);

  return (
    <select
      value={sortByHook.sortOption?.handle}
      onChange={handleSelectChange}
    >
      {sortByHook.sortOptions.map((sortOption) => (
        <option
          key={sortOption.handle}
          value={sortOption.handle}
        >
          {sortOption.name}
        </option>
      ))}
    </select>
  );
};

Signature

(): {
  /** The currently selected sort option */
  sortOption?: SortOption;
  /** All of the available sort options */
  sortOptions: Array<SortOption>;
  /** Function for changing the current sort option */
  setSortOption: (
    sortOptionHandle: string,
    ignoreHistoryState?: boolean
  ) => void;
};

SortOption = {
  id: string;
  name: string;
  handle: string;
  field: string;
  position: number;
  direction: "desc" | "asc";
  visibility: "all" | "search" | "collection";
};

Last updated