Last active
March 16, 2020 04:38
-
-
Save abhijitrakas/6e2e4d0d9d1843bee1204b2fab825043 to your computer and use it in GitHub Desktop.
Gutenberg built in autocomplete not working so this is custom one
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'; | |
const { withInstanceId } = wp.compose; | |
function Autocomplete( { | |
label, | |
value, | |
onChange, | |
options = [], | |
instanceId | |
} ) { | |
// Construct a unique ID for this block. | |
const blockId = `autocomplete-${ instanceId }`; | |
// 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 withInstanceId( Autocomplete ); |
Import this component in your file.
Then I used component something like below.
<Autocomplete
label={ __( 'Category' ) }
value={category}
options={categories}
onChange={ setCategory }
placeholder="Type to search categories..."
/>
Pass your categories array in options
, set on change event in onChange
and then set current selected category in value
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How would you implement this custom Autocomplete component?