Skip to content

Instantly share code, notes, and snippets.

@creationspirit
Created August 30, 2019 12:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save creationspirit/93e272195534256b7ed46d5c07af0446 to your computer and use it in GitHub Desktop.
Save creationspirit/93e272195534256b7ed46d5c07af0446 to your computer and use it in GitHub Desktop.
A custom Algolia React InstantSearch widget. It is a toggle refinement filtering on some attribute with 'greater than a given threshold' condition. One of my projects needed this feature and original library does not support this kind of widget so I made a custom one. Hope it helps to someone
import React from 'react';
import { createConnector } from 'react-instantsearch-dom';
const connect = createConnector({
displayName: 'GreaterThanRefinement',
getProvidedProps(props, searchState) {
const currentRefinement = searchState.greaterThan[props.attribute] || false;
return { currentRefinement };
},
refine(props, searchState, nextRefinement) {
return {
...searchState,
greaterThan: {
...searchState.greaterThan,
[props.attribute]: nextRefinement,
},
};
},
getSearchParameters(searchParameters, props, searchState) {
if (searchState.greaterThan[props.attribute]) {
return searchParameters.addNumericRefinement(props.attribute, '>', props.threshold);
}
return searchParameters;
},
cleanUp(props, searchState) {
const nextSearchState = {...searchState};
delete nextSearchState.greaterThan[props.attribute];
return nextSearchState;
},
});
const GreaterThanRefinement = ({ currentRefinement, refine, label }) => (
<form>
<label>
<input
type="checkbox"
checked={currentRefinement}
onClick={() => {refine(!currentRefinement);}}
/>
<span>{label}</span>
</label>
</form>
);
export default connect(GreaterThanRefinement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment