Skip to content

Instantly share code, notes, and snippets.

@thatdevgirl
Created November 29, 2018 15:29
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thatdevgirl/e20f72d5b985c6eab441bdf491b3edf0 to your computer and use it in GitHub Desktop.
Save thatdevgirl/e20f72d5b985c6eab441bdf491b3edf0 to your computer and use it in GitHub Desktop.
Simple Autocomplete component for WP Gutenberg
/**
* 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;
@mipon
Copy link

mipon commented Jan 16, 2022

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?

@thatdevgirl
Copy link
Author

@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