Created
November 29, 2018 15:29
-
-
Save thatdevgirl/e20f72d5b985c6eab441bdf491b3edf0 to your computer and use it in GitHub Desktop.
Simple Autocomplete component for WP Gutenberg
This file contains 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
/** | |
* A very simple autocomplete component | |
* | |
* This is to replace the OOTB Gutenberg Autocomplete component because it is | |
* currently broken as of v4.5.1. | |
* | |
* See Github issue: https://github.com/WordPress/gutenberg/issues/10542 | |
* | |
* Note: The options array should be an array of objects containing labels and values; i.e.: | |
* [ | |
* { value: 'first', label: 'First' }, | |
* { value: 'second', label: 'Second' } | |
* ] | |
*/ | |
// Load external dependency. | |
import { isEmpty } from 'lodash'; | |
function MyAutocomplete( { | |
label, | |
id, | |
value, | |
onChange, | |
options = [], | |
} ) { | |
// Construct a unique ID for this block. | |
const blockId = `my-autocomplete-${ id }`; | |
// Function to handle the onChange event. | |
const onChangeValue = ( event ) => { | |
onChange( event.target.value ); | |
}; | |
// Return the block, but only if options were passed in. | |
return ! isEmpty( options ) && ( | |
<div> | |
{ /* Label for the block. */ } | |
<label for={ blockId }> | |
{ label } | |
</label> | |
{ /* Input field. */ } | |
<input | |
list={ blockId } | |
value={ value } | |
onChange={ onChangeValue } | |
/> | |
{ /* List of all of the autocomplete options. */ } | |
<datalist id={ blockId }> | |
{ options.map( ( option, index ) => | |
<option value={ option.value } label={ option.label } /> | |
) } | |
</datalist> | |
</div> | |
); | |
}; | |
export default MyAutocomplete; |
This helped a lot. Thanks!
I get this error in the browser console every time an item is selected.
Uncaught TypeError: Cannot read properties of undefined (reading 'toLowerCase')
at HTMLDocument.eval (eval at <anonymous> (eval at ExRmtSvrCd (eval at <anonymous> (wit.js:206))), <anonymous>:1:29484)
By the way, is it possible to search posts by typing a partial post title?
@mipon I just tried and I am not seeing that error. (Testing on Chrome latest.) I am also curious about the error talking about toLowerCase
(which is not used by this component). I wonder if it is conflicting with something else in your code. Would you be comfortable sharing the code that is using the autocomplete component?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@techjewel The AutoComplete is a component that you can use more than once, just like any other component. So, expanding on my previous comment at https://gist.github.com/thatdevgirl/e20f72d5b985c6eab441bdf491b3edf0#gistcomment-2982019, you can do something like this: