Sajari React SDK ·
![license](http://img.shields.io/badge/license-MIT-green.svg?style=flat-square)
sajari-react is a client side javascript library of React Components for the Sajari search platform to help build fast and powerful search interfaces.
React provides a simple and elegant way to structure user interfaces. The Sajari React SDK provides a way to seamlessly integrate the Sajari platform into any web-based app through the use of easily composable Components.
We also provide a vanilla Sajari JS library here.
Table of contents
Examples
It's easy to get up and running using one of our examples as a starting point. They're pre-configured with all the correct dependencies, so all you need to do is copy the example directory into your own workspace and you're on your way!
Setup
Check out our examples for the best way to get started.
If you want to add the SDK to an existing project, or want to start from scratch, then you can get sajari-react
using NPM.
NPM
We currently distribute the sajari-react
library through NPM. NPM is only required for downloading the library. The SDK is made to be used from the browser.
$ npm install --save sajari sajari-react
Quick reference
This library includes a standard set of components for building search interfaces.
Setting up API calls
Before you can use any components, you'll need to initialise a Pipeline
for handling search requests to the API:
import { Pipeline } from "sajari-react/controllers";
const pipeline = new Pipeline("<your-project>", "<your-collection>", "website");
pipeline.search({
"q": "awesome articles",
});
AutocompleteInput
![autocomplete](https://media.giphy.com/media/26zyVB5UcumOfOInu/giphy.gif)
AutocompleteInput
provides a text-box which performs searches as the user types and renders appropraite autocomplete suggestions back in the input box.
import { AutocompleteInput } from "sajari-react/ui/text";
<AutocompleteInput values={values} pipeline={pipeline} />
Input
Input
is a plain search box which does not show autocomplete suggestions.
import { Input } from "sajari-react/ui/text";
<Input values={values} pipeline={pipeline} />
AutocompleteDropdown
AutocompleteDropdown
is a text box which performs autocomplete as the user types and renders autocomplete suggestions in a list underneath.
![autocomplete-suggest](https://media.giphy.com/media/xT39DnBWdmrxJ1Xd1S/giphy.gif)
import { AutocompleteDropdown } from "sajari-react/ui/text";
<AutocompleteDropdown values={values} pipeline={pipeline} />
Handling results
A typical search result UI could includes a summary of the search, maybe with options to change spellings or search for alternatives, and a list of the paginated results. We include components for all of these pieces so it's easy to get started.
A standard search response handler would look something like this:
<Response pipeline={pipeline}>
<Summary values={values} pipeline={pipeline} />
<Results pipeline={pipeline} />
<Paginator values={values} pipeline={pipeline} />
</Response>
<Response/>
The <Response />
component doesn't render its children if the pipeline Response
is empty (i.e. the initial pre-search state, or after pipeline.clearResponse()
has been called).
<Results />
The <Results />
component can also take a custom renderer which will be used to render its individual results. See the custom result renderer example for more details.
Building facets
Use the Filter
helper-class from sajari-react/controllers
to integrate facets into UI. The library provides a standard set of components under sajari-react/ui/facets
which can automatically bind state to Filter
instances. For more details, see the full documentation.
Single-select filters
A single-select filter is used to handle state for components that offer multiple filtering options but only allow one option to be enabled at any one time. For example: a drop-down box or group of radio buttons.
import { Filter } from "sajari-react/controllers";
const categories = new Filter(
{
"all": "",
"blog": "dir1='blog'",
"articles": "dir1='articles'"
},
"all"
);
Each filter is given a name (in this example: all
, blog
, articles
) which can then be used to bind them to UI components:
import { RadioFacet } from "sajari-react/ui/facets";
<div>
<h3>Categories</h3>
<RadioFacet filter={categories} name="all" /><label>All</label>
<RadioFacet filter={categories} name="blog" /><label>Blog</label>
<RadioFacet filter={categories} name="articles" /><label>Articles</label>
</div>
Or a drop-down select box:
import { SelectFacet } from "sajari-react/ui/facets";
<SelectFacet
filter={categories}
options={{
// Options: Name -> Display Name
all: "All",
blog: "Blog",
articles: "Articles"
}}
/>
To include the filter in a search it needs to be attached to the Values
instance used by Pipeline
:
import { selectionUpdatedEvent } from "sajari-react/controllers";
values.set({ filter: () => categories.filter() });
categories.listen(selectionUpdatedEvent, () => pipeline.search(values.get()));
Multi-select filters
A multi-select filter is used to represent state for UI components that can have multiple options selected at once, i.e. a list of check boxes or a multi-select list.
const categories = new Filter(
{
"blog": "dir1='blog'",
"articles": "dir1='articles'",
"other": "dir1!='blog' AND dir1!='articles'",
},
["blog", "articles"],
true,
);
This can be hooked up to a list of checkboxes:
import { CheckboxFacet } from "sajari-react/ui/facets";
<div>
<h3>Categories</h3>
<CheckboxFacet filter={categories} name="blog" /><label>Blog</label>
<CheckboxFacet filter={categories} name="articles" /><label>Articles</label>
<CheckboxFacet filter={categories} name="other" /><label>Other</label>
</div>
The default operator used to combine selected filters is OR
, but this can be overriden by the last argument in the Filter
construtor. See the full class docs for more details.
To include the filter in a search it needs to be attached to the Values
instance used by Pipeline
:
import { selectionUpdatedEvent } from "sajari-react/controllers";
values.set({ filter: () => categories.filter() });
categories.listen(selectionUpdatedEvent, () => pipeline.search(values.get()));
Tidying up filter listeners
The listen
method returns a closure that will unregister the new listener:
const unregister = filter.listen(selectionUpdatedEvent, () => {
console.log("filter changed:", filter.filter());
});
unregister();
Combining multiple filters
To combine multiple Filter
instances into one, use the CombineFilters
function.
import { selectionUpdatedEvent } from "sajari-react/controllers";
const recencyFilter = new Filter(...);
const categoryFilter = new Filter(...);
const filter = CombineFilters([recencyFilter, categoryFilter])
values.set({ filter: () => filter.filter() })
const unregister = filter.listen(selectionUpdatedEvent, () => {
pipeline.search(values.get());
});
unregister();
Using Values
The Values
convenience class used to manage parameters for running searches.
import { Values } from "sajari-react/controllers";
const values = new Values({ resultsPerPage: "5" });
Setting values
Use to the set
method to set values in an instance of Values
:
values.set({ "q": "search query" });
It's also possible to assign closures to value keys, these will be evaluated whenever Values.get()
is called (i.e. pipeline.search(values.get())
).
values.set({ hello: () => "Hello" })
Listening for changes
Register listeners to be notified of changes to a Values
instance (via valuesUpdatedEvent
). All listeners are passed the dictionary of values that were updated and a set function will set a new value without triggering another valuesUpdatedEvent
.
import { valuesUpdatedEvent } from "sajari-react/controllers";
const unregister = values.listen(valuesUpdatedEvent, (updated, set) => {
if (!updated.page) {
set({ page: "1" });
}
console.log("values: ", values.get());
});
unregister();
Using Pipeline
The Pipeline
controller handles all the search request/response lifecycle.
import { Pipeline } from "sajari-react/controllers";
const pipeline = new Pipeline("<your-project>", "<your-collection>", "website");
Performing searches
To perform a search you need a dictionary of parameter key-value pairs.
pipeline.search({
q: "search keywords",
filter: "dir1='articles'"
});
Listening for responses
Register listeners to be notified when search responses come back from the server, or are cleared by UI events. Every listener is passed a Response
which wraps the server response with convenience methods:
isEmpty()
: returns true
if the response is empty (i.e. as a result of a call to Pipeline.clearResponse()
)isError()
: returns true
if the response is an error response.getError()
: returns the underlying error.getResponse()
: returns the full search response.getResults()
: returns the search results from the response.getTotalResults()
: returns the total results found.getTime()
: returns the total query time.getAggregates()
: returns aggregate data attached to response.
import { responseUpdatedEvent } from "sajari-react/controllers";
const unregister = pipeline.listen(responseUpdatedEvent, (response) => {
if (response.isEmpty()) {
console.log("empty response");
return;
}
if (response.isError()) {
console.error("error response:", response.getError());
return;
}
response.getResults().forEach((result) => {
console.log(result);
})
});
License
We use the MIT license
Browser support
The browser support is dependent on the React library, which currently supports recent versions of Chrome, Firefox, Sajari, Opera, and IE9+. (17/8/2016)