Blocks: set a default value for a TextControl


I’m creating a block similar to the WP Core Table block, which first presents the user with a form to set the number of rows and columns. I’d like to set a default value in the TextControl for the number of columns.

Here’s a highly simplified version of the block:

const { registerBlockType } = wp.blocks; 
var el = wp.element.createElement;
const { TextControl } = wp.components;

registerBlockType( 'cgb/a11ytable', {
    title: 'Accessible Table',
    icon: 'screenoptions',
    category: 'common',
    attributes: {
        numCols: {
            type: 'number'
    edit: (props) => {
        const { attributes: { numCols }, className, setAttributes } = props;
        return [
                TextControl, {
                    label: 'Number of Columns',
                    type: 'number',
                    value: 2, // this is the problem line
                    onChange: function(value) {
                        props.setAttributes({ numCols: value })
    save: ( props ) => {
        var attributes = props.attributes;
        return el('table', { className: props.classes },
} );

The problem is, when the value of the TextControl is set to anything, as above (even when it is changed from just plain 2 to “2”), once the block is added in the editor, it’s not possible to change the value. The up and down arrows which appear because it’s type:number don’t allow the number to change, and typing inside the input is disabled (you get a cursor, but can’t select, add, or delete the 2).

The Gutenberg Handbook doesn’t seem to go over syntax to set a default value. I don’t think it needs a state, as this input just sends data to another function that creates the table itself and saves the value to an attribute for later calculations, it’s not something the user can continue to manipulate.

, WebElaine 3 years 2020-06-04T08:10:38-05:00 0 Answers 109 views 0

Leave an answer