Search code examples
wordpresswordpress-gutenberggutenberg-blocks

WP Gutenberg, how to import EditableText (as an alternative to RichText )?


I need a Gutenberg block that asks for a string without format

So instead of using RichText, I'd say EditableText is the component that I need

Documentation here https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/editable-text

In my code the problem is that I cannot even import the component

import { EditableText } from '@wordpress/block-editor'
//import { EditableText } from '@wordpress/components'
import { RichText  } from '@wordpress/block-editor'

console.log(EditableText) // nothing
console.log(RichText)

I can see the RichText lives in wp.editor and in wp.blocEditor, but I cannot find EditableText anywhere

Why is that? Is this element deprecated? If so, what would be an alternative to add an input block without formatting?

EDIT: I can always use a plain <input> element, as said here https://developer.wordpress.org/block-editor/developers/richtext/#unwanted-formatting-options-still-display but I'd like to know why EditableText is not available or how I can import it


Solution

  • I think this is because the EditableText block is not stable yet, in the current version, I can see that that it is based on the RichText component:

    import RichText from '../rich-text';
    
    const EditableText = forwardRef( ( props, ref ) => {
        return (
            <RichText
                ref={ ref }
                { ...props }
                __unstableDisableFormats
                preserveWhiteSpace
            />
        );
    } );
    

    Unfortunately, it crashes when I try to use it (I may be doing it wrong), and using the RichText as the code from EditableText suggests does not work.

    Solution : the documentation of RichText indicates that you can use the formattingControls attribute even though it is not recommended for "just text input": https://developer.wordpress.org/block-editor/developers/richtext/#unwanted-formatting-options-still-display

    Alternatively, to get a "pure" Gutenberg implementation of your input field, you can use TextControl (beware of the imports in the example, it is located in @wordpress/components and not @wordpress/blocks):

    import { TextControl } from '@wordpress/components';
    import { withState } from '@wordpress/compose';
    
    const MyTextControl = withState( {
        className: '',
    } )( ( { className, setState } ) => ( 
        <TextControl
            label="Additional CSS Class"
            value={ className }
            onChange={ ( className ) => setState( { className } ) }
        />
    ) );