Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bussiere/c29aaaffa2eee1f2446229229fd8d6f0 to your computer and use it in GitHub Desktop.
Save bussiere/c29aaaffa2eee1f2446229229fd8d6f0 to your computer and use it in GitHub Desktop.
Autocomplete group results - @trevoreyre/autocomplete-js

Autocomplete group results - @trevoreyre/autocomplete-js

Example of an autocomplete component using a custom renderResult function to control of rendering of items in the results list, and grouping the results into groups of 3. Using the @trevoreyre/autocomplete-js package from npm.

A Pen by Trevor Eyre on CodePen.

License.

<div id="autocomplete" class="autocomplete">
<input class="autocomplete-input"
placeholder="Search Wikipedia"
aria-label="Search Wikipedia"
>
<ul class="autocomplete-result-list"></ul>
</div>
console.clear()
const wikiUrl = 'https://en.wikipedia.org'
const params = 'action=query&list=search&format=json&origin=*'
new Autocomplete('#autocomplete', {
// Search function can return a promise
// which resolves with an array of
// results. In this case we're using
// the Wikipedia search API.
search: input => {
const url = `${wikiUrl}/w/api.php?${
params
}&srsearch=${encodeURI(input)}`
return new Promise(resolve => {
if (input.length < 3) {
return resolve([])
}
fetch(url)
.then(response => response.json())
.then(data => {
const results = data.query.search.map((result, index) => {
return { ...result, index }
})
resolve(results)
})
})
},
// Control the rendering of result items.
// Let's show the title and snippet
// from the Wikipedia results
renderResult: (result, props) => {
let group = ''
if (result.index % 3 === 0) {
group = `<li class="group">Group</li>`
}
return `
${group}
<li ${props}>
<div class="wiki-title">
${result.title}
</div>
<div class="wiki-snippet">
${result.snippet}
</div>
</li>
`
},
// Wikipedia returns a format like this:
//
// {
// pageid: 12345,
// title: 'Article title',
// ...
// }
//
// We want to display the title
getResultValue: result => result.title,
// Open the selected article in
// a new window
onSubmit: result => {
window.open(`${wikiUrl}/wiki/${
encodeURI(result.title)
}`)
}
})
<script src="https://unpkg.com/@trevoreyre/autocomplete-js"></script>
<script src="https://codepen.io/trevoreyre/pen/LqBPzY"></script>
#autocomplete {
max-width: 400px;
margin: 0 auto;
}
.autocomplete-result {
border-top: 1px solid #eee;
padding: 16px;
background: transparent;
}
.group {
padding: 16px;
text-transform: uppercase;
font-size: 14px;
background: rgba(0, 0, 0, 0.06);
}
.wiki-title {
font-size: 20px;
margin-bottom: 8px;
}
.wiki-snippet {
font-size: 14px;
color: rgba(0, 0, 0, 0.54);
}
<link href="https://unpkg.com/@trevoreyre/autocomplete-js/dist/style.css" rel="stylesheet" />
<link href="https://codepen.io/trevoreyre/pen/LqBPzY" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment