Show and Tell: the WordPress FormTokenField Component

Photo of hashtag puzzle pieces
Hashtags – License: Adobe Stock

The FormTokenField component is useful for outputting tags, hashtags, users, or any token format.

For QuotesDLX, I used the component in both the block editor and the admin area. I use it for hashtag output, as you can see in the example below.

Adding Hashtags to the Form Token Field
Adding Hashtags to the Form Token Field

FormTokenField in the admin panel

For my React screen, I needed to use the FormTokenField component to display and provide an interface for inputting hashtags.

First was including it via @wordpress/components.

Form Token Field WP Components
Form Token Field WP Components

I then use React Hook Form to control the saving/outputting using their handy controller.

<Controller
	name="hashtags"
	control={ control }
	render={ ( { field: { onChange, value } } ) => (
		<FormTokenField
			value={ value }
			placeholder={ __(
				'Enter hashtags separated by commas.',
				'quotes-dlx'
			) }
			className="quotes-dlx-hashtag-fields"
			tokenizeOnSpace={ true }
			label={ __( 'Hashtags', 'quotes-dlx' ) }
			onChange={ ( tokens ) => {
				const filteredTokens = [];
				tokens.forEach( function( item, index ) {
					const replacement = item.replace( '#', '' ); // Strip hashtag symbol.
					const hashtag = twttr.txt.extractHashtags(
						'#' + replacement
					); // Add it back in for extraction.
					// Check if array contains anything.
					if ( typeof hashtag[ 0 ] !== 'undefined' ) {
						filteredTokens.push( hashtag[ 0 ] );
					}
				} );
				onChange( filteredTokens );
			} }
		/>
	) }
/>Code language: JavaScript (javascript)

There are some notable attributes, so let’s go over each one I use.

The value attribute

The value attribute accepts an array of tokens. An example of this array can be found in the FormTokenField documentation:

const continents = [
    'Africa',
    'America',
    'Antarctica',
    'Asia',
    'Europe',
    'Oceania',
];Code language: JavaScript (javascript)

When you pass or update this value, the FormTokenField component will update automatically with “tokens.”

The placeholder attribute

placeholder={ __(
	'Enter hashtags separated by commas.',
	'quotes-dlx'
) }Code language: JavaScript (javascript)

The placeholder attribute is what displays if there currently isn’t any input.

Placeholder for the FormTokenField Component
Placeholder for the FormTokenField Component

The tokenizeOnSpace attribute

If passed true, when a user enters a space, it will create a token.

tokenizeOnSpace={ true }Code language: JavaScript (javascript)

The label attribute

The label is simply what’s shown above the input field.

label={ __( 'Hashtags', 'quotes-dlx' ) }Code language: JavaScript (javascript)

The onChange attribute

The onChange attribute triggers every time there’s an addition or removal of a token from the FormTokenField component.

onChange Handler for FormTokenField
onChange Handler for FormTokenField

FormTokenField in Blocks

Hashtags in the Block Editor
Hashtags in the Block Editor

The way I used hashtags in the block editor is very similar to how I used the FormTokenField component in the admin.

Since we’re in the context of blocks, I’ll show you how I registered the block attributes. The following assumes you’re using block.json for your blocks.

Hashtag Attribute as an Array
Hashtag Attribute as an Array

You’ll notice that the hashtags are of type array with a default of: []

And here’s the code for displaying and saving the attribute.

<FormTokenField
	value={ hashtags }
	placeholder={ __(
		'Enter hashtags separated by commas.',
		'quotes-dlx'
	) }
	className="quotes-dlx-hashtag-fields"
	tokenizeOnSpace={ true }
	label={ __( 'Hashtags', 'quotes-dlx' ) }
	onChange={ ( tokens ) => {
		const filteredTokens = [];
		tokens.forEach( function( item, index ) {
			const replacement = item.replace( '#', '' ); // Strip hashtag symbol.
			const hashtag = twttr.txt.extractHashtags(
				'#' + replacement
			); // Add it back in for extraction.
			// Check if array contains anything.
			if ( typeof hashtag[ 0 ] !== 'undefined' ) {
				filteredTokens.push( hashtag[ 0 ] );
			}
		} );
		setAttributes( { hashtags: filteredTokens } );
	} }
/>Code language: JavaScript (javascript)

You’ll notice at the very end of the onChange attribute, that I call setAttributes to save the hashtags in the block editor.

Conclusion

The FormTokenField component is pretty useful if you have an array of tokens, tags, hashtags, etc. If you have any questions, I’ll reply in the comments.

Ronald Huereca
By: Ronald Huereca
Published On: on February 4, 2023

Ronald Huereca founded DLX Plugins in 2022 with the goal of providing deluxe plugins available for download. Find out more about DLX Plugins, check out some tutorials, and check out our plugins.

Leave Your Valuable Feedback

Your email address will not be published. Required fields are marked *

Shopping Cart
  • Your cart is empty.
Scroll to Top