@lableb/react-sdk
v3.0.1
Published
React Components and hooks to integrate with Lableb Cloud Search
Downloads
48
Readme
Lableb Cloud Search React SDK
Add Great Search user experience
Easy, Small, configurable UI library that allow instant integration with Lableb
Install
yarn add @lableb/react-sdk # or: npm i @lableb/react-sdk
Install Peer Dependencies
yarn add @lableb/javascript-sdk axios yup
For Server side apps' bundlers
Note: For SSR tech, like next.js you have to alias
react
andreact-dom
in your configuration because they are used aspeer-dependencies
in this library
webpack(config) {
config.resolve.alias = {
...config.resolve.alias,
'react': path.resolve(__dirname, './node_modules/react'),
'react-dom': path.resolve(__dirname, './node_modules/react-dom'),
'@lableb/javascript-sdk': path.resolve(__dirname, './node_modules/@lableb/javascript-sdk/dist/index'),
}
return config;
}
How to use
1. Wrap all Lableb's components and hooks within LablebProvider
import { LablebProvider, GlobalOptions } from '@lableb/react-sdk';
const SDK_OPTIONS: GlobalOptions = {
platformName: 'project-name',
APIKey: 'gXPg561985-F-jxboFtqEK100trmgk-OpLsA',
}
export default function Home() {
return (
<LablebProvider options={SDK_OPTIONS}>
{'...'}
</LablebProvider>
);
}
2. Use Built-in UI components from the library
import {
LablebProvider,
LablebSearch,
LablebFilters,
LablebPagination,
LablebSearchResults,
} from '@lableb/react-sdk';
const SDK_OPTIONS = {
APIKey: 'gXPg561979-F-jxboFtqEK96trmgk-OpLsA',
platformName: 'shopify-arch',
}
export default function Home() {
return (
<LablebProvider options={SDK_OPTIONS}>
<LablebSearch />
<div className="flex justify-between">
<LablebFilters />
<LablebSearchResults />
</div>
<LablebPagination />
</LablebProvider>
);
}
Build your own UI using Lableb's reactive hooks
Search Hooks
Fetch search results: useSearchResults
function App(){
const searchResults = useSearchResults();
return (
<div>
{
searchResults?.map((lablebDocument: any) => (
<ResultCard
key={lablebDocument.id}
lablebDocument={lablebDocument}
...
/>
))
}
</div>
);
}
Get search loading state: useIsSearchLoading
function App(){
const loading = useIsSearchLoading();
if(loading)
return <SearchLoader/>;
return (
<div>
...
</div>
);
}
Get a reference to search function: useLablebSearch
function App(){
const search = useLablebSearch();
return (
<div>
<input
...
/>
<button onClick={search}>
{'Search'}
</button>
</div>
);
}
Access and Set search query: useSearchQuery & useSetSearchQuery
function App(){
const query = useSearchQuery();
const setQuery = useSetSearchQuery();
return (
<div>
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
</div>
);
}
Get Search results count: useTotalSearchDocumentsCount
function App(){
const searchResultsCount = useTotalSearchDocumentsCount();
return (
<div>
<span>{`Found: ${searchResultsCount} results`}</span>
</div>
);
}
Get Search total time: useTotalSearchTime
function App(){
const searchTime = useTotalSearchTime();
return (
<div>
<span>{`Search takes: ${searchTime} ms`}</span>
</div>
);
}
Search feedback: useSearchFeedback
export function App() {
const searchResults = useAutocompleteResults();
const sendFeedback = useAutocompleteFeedback();
return (
<div className={classes.resultsContainer}>
{
searchResults?.map((lablebDocument) => (
<ResultCard
key={lablebDocument.id}
lablebDocument={lablebDocument}
onClick={() => sendFeedback(lablebDocument.feedback)}
/>
))
}
</div>
);
}
Autocomplete Hooks
Fetch autocomplete results: useAutocompleteResults
function App(){
const autocompleteResults = useAutocompleteResults();
return (
<div>
{
autocompleteResults?.map((result, index) => (
<div
key={`${result?.phrase}-${index}`}
>
<span className={classes.autocompletePhrase}>
{result?.phrase}
</span>
<span>
{result?.type || result?.suggestion_type || ''}
</span>
</div>
))
}
</div>
);
}
Autocomplete loading state: useIsAutocompleteLoading
function App(){
const loading = useIsAutocompleteLoading();
if(loading)
return <AutocompleteLoader />;
return (
<div>
...
</div>
);
}
Autocomplete feedback: useAutocompleteFeedback
export function App() {
const autocompleteResults = useAutocompleteResults();
const sendFeedback = useAutocompleteFeedback();
return (
<div className={classes.resultsContainer}>
{
autocompleteResults?.map((lablebDocument) => (
<ResultCard
key={lablebDocument.id}
lablebDocument={lablebDocument}
onClick={() => sendFeedback(lablebDocument.feedback)}
/>
))
}
</div>
);
}
Recommend Hooks
Fetch recommend results: useRecommend
function App(){
const recommendResults = useRecommend();
return (
<div>
{
recommendResults?.map((lablebDocument: any) => (
<ResultCard
key={lablebDocument.id}
lablebDocument={lablebDocument}
...
/>
))
}
</div>
);
}
Recommend Loading State: useIsRecommendLoading
function App(){
const loading = useIsRecommendLoading();
if(loading)
return <RecommendLoader />;
return (
<div>
...
</div>
);
}
Recommend feedback: useRecommendFeedback
export function App() {
const recommendResults = useRecommend({ id: '123' });
const sendFeedback = useRecommendFeedback();
return (
<div className={classes.resultsContainer}>
{
recommendResults?.map((lablebDocument) => (
<ResultCard
key={lablebDocument.id}
lablebDocument={lablebDocument}
onClick={() => sendFeedback(lablebDocument.feedback)}
/>
))
}
</div>
);
}
Search Results Pagination
use pagination utility: usePagination
export function App(){
const {
next,
prev,
page,
hasNextPage,
hasPrevPage,
changePage,
totalDocuments,
totalPages,
hasNextTenPage,
hasPrevTenPage,
nextTen,
prevTen,
} = usePagination();
return (
<div>
<button onClick={next}>
{'Next Page'}
</button>
<span>
{page}
</span>
<button onClick={prev}>
{'Previous Page'}
</button>
</div>
);
}
Search Filters
Get search filters: useFilters
import { LablebFacets, useFilters } from '@lableb/react-sdk';
export function App(){
const filters: LablebFacets = useFilters();
...
}
where LablebFacets has the following:
export interface LablebFacets {
[key: string]: {
buckets: LablebFacet[];
};
}
export interface LablebFacet {
value: string;
count: number;
}
Get user selected filters: useSelectedFilters
import { SelectedFilters } from '@lableb/react-sdk';
export function App(){
const filters: SelectedFilters = useSelectedFilters();
...
}
where the type of SelectedFilters is:
export interface SelectedFilters {
[key: string]: string[];
}
Toggle a filter & check if a filter is already selected: useFilterToggle & useIsSelected
export function FiltersValues({ facetName }:{ facetName:string }){
const toggle = useFilterToggle();
const isSelected = useIsSelected(facetName);
// rendering filter values
return (
...
<div>
<p>{facetName}</p>
<div>
{
buckets
?.map(({ value, count }) => (
<div key={`${facetName}-${value}`}>
<input
id={`${facetName}-${value}-${count}`}
type="checkbox"
checked={isSelected(value)}
onChange={() => toggle({ facetName, facetValue: value })}
/>
<label htmlFor={`${facetName}-${value}-${count}`}>
{value}
</label>
</div>
))
}
</div>
</div>
);
}
reset all filters: useReset
export function App(){
const reset = useReset();
return (
<div>
<button onClick={reset}> {'Reset Filters'} </button>
</div>
);
}
Get the globally defined range filters: useRangeFilters
export function App(){
const rangeFiltersArray = useRangeFilters();
...
}
where Range filters defined as
export interface SDKRangeFilter {
filterName: string,
max?: number,
min?: number,
step?: number,
}
Global Options
| property | type | default | description | | --------------------- | -------| --------- | --------------- | | platformName* | string | - | Your platform name as written at Lableb Dashboard | | APIKey* | string | - | Search, Autocomplete, Recommend, and Feedback API Key | | indexName | string | index | The used data index name as created at Lableb Dashboard | Collections | | indexingAPIKey | string | - | Index, Delete API Key | | searchHandler | string | default | The used search handler name as found at Lableb Dashboard | Collections | Handlers | | autocompleteHandler | string | suggest | The used autocomplete handler name as found at Lableb Dashboard | Collections | Handlers | | recommendHandler | string | recommend | The used recommend handler name as found at Lableb Dashboard | Collections | Handlers | | interceptors | array of functions | [] | pass an array of interceptors functions to manipulate the request before being sent to Lableb. Read in details | | userId | string | - | end user id | | userIp | string | - | end user IP address | | userCountry | string | - | end user country code(ISO-3166) | | sessionId | string | - | uniques session Id for your end user | | sessionIdGenerator | function | - | pass callback that generate unique session id string | | defaultSelectedFilters | DefaultSelectedFilter[] | - | Array of selected filters names and values that will persist | | dir | "rtl" or "ltr" | "ltr" | the direction of the root component | | hiddenFilters | string[] | - | filters names that will not be returned in search filters results | | rangeFilters | SDKRangeFilter[] | - | specify which filter will be displayed as range filter | | collectRangeFilters | "first" or "last" | - | where to render range filters in relative to other search filters |
Selected Filters Type
export interface DefaultSelectedFilter {
filterName: string,
filterValues: string[],
}
Range Filter Type
export interface SDKRangeFilter {
filterName: string,
max?: number,
min?: number,
step?: number,
}