Created
April 18, 2022 14:56
-
-
Save ssdeniss/9c17d7dc9f4078bbd8c41272cf88caba to your computer and use it in GitHub Desktop.
Autocomplete search results with React (Bing Autosuggest API, Semantic UI Search)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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