useSortBy

Purpose

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

Usage

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?: ConfigSort;
  /** All of the available sort options */
  sortOptions: Array<ConfigSort>;
  /** Function for changing the current sort option */
  setSortOption: (
    sortOptionHandle: string,
    ignoreHistoryState?: boolean
  ) => void;
}

Last updated