Skip to content

Instantly share code, notes, and snippets.

@arnaudrenaud
Last active April 18, 2022 14:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save arnaudrenaud/70d21dcbc20acf2d287143880a18a63b to your computer and use it in GitHub Desktop.
Save arnaudrenaud/70d21dcbc20acf2d287143880a18a63b to your computer and use it in GitHub Desktop.
Autocomplete search results with React (Bing Autosuggest API, Semantic UI Search)
import React, { Component } from "react";
import { Search } from "semantic-ui-react";
import _ from "lodash";
import logo from "./logo.svg";
import SelectedResult from "./SelectedResult";
import "./App.css";
class App extends Component {
state = { results: [], selectedResult: null };
handleSearchChange = async (event, { value }) => {
try {
const response = await fetch(
`https://api.cognitive.microsoft.com/bing/v7.0/suggestions?mkt=fr-FR&q=${value}`,
{
headers: {
"Ocp-Apim-Subscription-Key": "917c08bb69d34a30a95f237a1832b1a3"
}
}
);
const data = await response.json();
const resultsRaw = data.suggestionGroups[0].searchSuggestions;
const results = resultsRaw.map(result => ({ title: result.displayText, url: result.url }));
this.setState({ results });
} catch (error) {
console.error(`Error fetching search ${value}`);
}
};
handleResultSelect = (e, { result }) =>
this.setState({ selectedResult: result });
render() {
return (
<div className="App">
<Search
onSearchChange={_.debounce(this.handleSearchChange, 1000, {
leading: true
})}
results={this.state.results}
onResultSelect={this.handleResultSelect}
/>
<SelectedResult result={this.state.selectedResult} />
</div>
);
}
}
export default App;
import React from "react";
const SelectedResult = ({ result }) => (
<a style={{ color: "red" }} href={result && result.url}>
{result && result.title}
</a>
);
export default SelectedResult;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment