Skip to content

Instantly share code, notes, and snippets.

@ItsWendell
Last active February 26, 2020 20:10
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 ItsWendell/1d1d69d048bc63e9189d3e48ce35d018 to your computer and use it in GitHub Desktop.
Save ItsWendell/1d1d69d048bc63e9189d3e48ce35d018 to your computer and use it in GitHub Desktop.
React Hooks: Algolia Places component with custom input field and support for initial value. (places.js)
import React, { useRef, useEffect } from 'react';
import places from 'places.js';
// Custom component for React implementation with Hooks for Places.js
const AlgoliaPlaces = ({
inputComponent = input,
placeholder,
options,
initialValue,
onChange = null,
onSuggestions = null,
onCursorChanged = null,
onClear = null,
onLimit = null,
onError = null,
}) => {
const inputEl = useRef(null);
useEffect(() => {
// Setup initial autocomplete object.
const autocomplete = places({
appId: process.env.ALGOLIA_PLACES_APP_ID, // Check process.env (dotenv nextjs)
apiKey: process.env.ALGOLIA_PLACES_API_KEY, // Check process.env (dotenv nextjs)
...options,
container: inputEl.current,
});
// Setup events if setup as properties.
if (onChange) { autocomplete.on('change', onChange); }
if (onClear) { autocomplete.on('clear', onClear); }
if (onCursorChanged) { autocomplete.on('cursorchanged', onCursorChanged); }
if (onError) { autocomplete.on('error', onError); }
if (onLimit) { autocomplete.on('limit', onLimit); }
if (onSuggestions) { autocomplete.on('suggestions', onSuggestions); }
// Set initial value (should be text)
if (initialValue) {
autocomplete.setVal(initialValue);
}
// When component gets detroyed
return () => {
autocomplete.removeAllListeners('change');
autocomplete.removeAllListeners('clear');
autocomplete.removeAllListeners('cursorchanged');
autocomplete.removeAllListeners('error');
autocomplete.removeAllListeners('limit');
autocomplete.removeAllListeners('suggestions');
autocomplete.destroy();
};
}, []);
const Component = inputComponent;
return (
<Component placeholder={placeholder} ref={inputEl} />
);
};
export default AlgoliaPlaces;
@ItsWendell
Copy link
Author

Quickly edited my implementation, might not instantly work, let me know if you need help implementing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment