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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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?