Skip to content

Instantly share code, notes, and snippets.

@abhijitrakas
Last active March 16, 2020 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhijitrakas/6e2e4d0d9d1843bee1204b2fab825043 to your computer and use it in GitHub Desktop.
Save abhijitrakas/6e2e4d0d9d1843bee1204b2fab825043 to your computer and use it in GitHub Desktop.
Gutenberg built in autocomplete not working so this is custom one
/**
* 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 );
@dexter-adams
Copy link

How would you implement this custom Autocomplete component?

@abhijitrakas
Copy link
Author

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