Skip to content

[IN-317]: React Native autosuggest example #65

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
coverage/
dist/
node_modules/
examples/
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -212,3 +212,5 @@ $RECYCLE.BIN/
.dccache

pacts/

.idea
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ A JavaScript library to make requests to the [what3words REST API][api]. __Now w
* [Examples](#examples)
* [CustomTransport](#custom-transport)
* [Autosuggest](#autosuggest)
* [React Native Autosuggest](examples/react-native/autosuggest/readme.md)
* [Convert to Coordinates](#convert-to-coordinates)
* [Convert to Three Word Address](#convert-to-three-word-address)
* [Available Languages](#available-languages)
Expand Down
19 changes: 19 additions & 0 deletions examples/react-native/autosuggest/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
node_modules/
.expo/
dist/
npm-debug.*
*.jks
*.p8
*.p12
*.key
*.mobileprovision
*.orig.*
web-build/

# macOS
.DS_Store

# Temporary files created by Metro to check the health of the file watcher
.metro-health-check*

.idea
212 changes: 212 additions & 0 deletions examples/react-native/autosuggest/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
import { StatusBar } from 'expo-status-bar';
import {
FlatList,
Pressable,
StyleSheet,
Text,
TextInput,
View,
} from 'react-native';
import {
AutosuggestClient,
AutosuggestInputType,
type AutosuggestOptions,
type AutosuggestSuggestion,
} from '@what3words/api';
import { useState } from 'react';

const API_KEY = '<YOUR_API_KEY>';
const DEBOUNCE_TIME = 300;

const client: AutosuggestClient = AutosuggestClient.init(API_KEY);

const white = '#ffffff';
const blue = '#0a3049';
const red = '#e11f26';
const lightGrey = '#e0e0e0';
const lightBlue = '#dbeffa';

let timeoutId: NodeJS.Timeout | null = null;

export default function App() {
const [search, setSearch] = useState<string>('');
const [suggestions, setSuggestions] = useState<AutosuggestSuggestion[]>([]);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [error, setError] = useState<Error | null>(null);

/**
* Fetch suggestions from the API when the search input value changes
* @param {string} search The search input value
* @returns {Promise<void>}
*/
async function handleOnSearch(search: string): Promise<void> {
setSearch(search);

// Cancel previous request before sending a new one
if (timeoutId) clearTimeout(timeoutId);

// Don't search if the input is empty
if (!search) return setSuggestions([]);

// Debounce the request to avoid sending too many requests while the user is typing
timeoutId = setTimeout(async () => {
try {
setIsLoading(true);
setError(null);
const options: AutosuggestOptions = {
input: search,
inputType: AutosuggestInputType.Text,
nResults: 3,
// Uncomment the following options to restrict the search
// focus: { lat: 51.521251, lng: -0.203586 },
// clipToCountry: ['GB'],
// clipToCircle: { center: { lat: 51.521, lng: -0.343 }, radius: 142 },
// clipToBoundingBox: {
// southwest: { lat: 51.521, lng: -0.343 },
// northeast: { lat: 52.6, lng: 2.3324 },
// },
// clipToPolygon: [
// { lat: 51.521, lng: -0.343 },
// { lat: 52.6, lng: 2.3324 },
// { lat: 54.234, lng: 8.343 },
// { lat: 51.521, lng: -0.343 },
// ],
// language: 'en',
// preferLand: true,
};

const { suggestions } = await client.run(options);

if (!suggestions.length) {
throw new Error('No valid 3 word address found.');
}

setSuggestions(suggestions);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
}
}, DEBOUNCE_TIME);
}

/**
* Set the selected suggestion words as the search input value and clear the suggestions list
* @param {AutosuggestSuggestion} sug The selected suggestion
*/
function handleSuggestionPress(sug: { item: AutosuggestSuggestion }): void {
setSearch(sug.item.words);
setSuggestions([]);
}

/**
* Render a suggestion as a Pressable RN component
* @param {AutosuggestSuggestion} sug The suggestion to render
* @returns {JSX.Element}
*/
const renderItem = (sug: { item: AutosuggestSuggestion }): JSX.Element => (
<Pressable
onPress={() => handleSuggestionPress(sug)}
style={({ pressed }) => [
styles.suggestion,
pressed ? { backgroundColor: lightBlue } : {},
]}>
<Text style={styles.suggestionWords}>
<Text style={styles.suggestionTripleSlash}>///</Text>
{sug.item.words}
</Text>
<Text style={styles.suggestionNearestPlace}>
{sug.item.nearestPlace}, {sug.item.country}
</Text>
</Pressable>
);

const showErrorMessage = !isLoading && !suggestions.length && error;

return (
<View style={styles.container}>
<StatusBar style="auto" />

<View style={styles.inputWrapper}>
<TextInput
style={styles.input}
placeholder="/// filled.count.soap"
onChangeText={handleOnSearch}
value={search}
cursorColor={blue}
autoCapitalize="none"
autoComplete="off"
autoCorrect={false}
autoFocus={true}
/>
{showErrorMessage && (
<Text style={styles.errorMessage}>{error.message}</Text>
)}
</View>

<FlatList
style={styles.suggestions}
data={suggestions}
keyExtractor={sug => sug.words}
renderItem={renderItem}
/>
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
paddingVertical: 48,
backgroundColor: white,
alignItems: 'center',
justifyContent: 'flex-start',
},
inputWrapper: {
width: '100%',
},
input: {
height: 48,
width: '100%',
color: blue,
paddingVertical: 8,
paddingHorizontal: 16,
fontSize: 20,
borderWidth: 1,
borderColor: lightGrey,
},
suggestions: {
flex: 1,
width: '100%',
backgroundColor: white,
},
suggestion: {
flex: 1,
width: '100%',
flexDirection: 'column',
paddingVertical: 8,
paddingHorizontal: 16,
backgroundColor: white,
borderWidth: 1,
borderTopColor: 'transparent',
borderColor: lightGrey,
},
suggestionTripleSlash: {
color: red,
},
suggestionWords: {
fontSize: 20,
fontWeight: 'bold',
color: blue,
marginBottom: 4,
},
suggestionNearestPlace: {
fontSize: 16,
color: blue,
},
errorMessage: {
color: red,
paddingVertical: 4,
},
});
30 changes: 30 additions & 0 deletions examples/react-native/autosuggest/app.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"expo": {
"name": "autosuggest",
"slug": "autosuggest",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"userInterfaceStyle": "light",
"splash": {
"image": "./assets/splash.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"assetBundlePatterns": [
"**/*"
],
"ios": {
"supportsTablet": true
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff"
}
},
"web": {
"favicon": "./assets/favicon.png"
}
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/react-native/autosuggest/assets/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions examples/react-native/autosuggest/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = function(api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
};
};
Loading