How to get the ToggleControl Gutenberg component working for a PHP Block

The issue is that in ToggleControl you are using the wrong prop for the value. It should be checked instead of value.

Also use the blockEditor package instead of editor for InspectorControls as it will be deprecated.


el(
    ToggleControl,
    {
        label: 'Toogle',
        checked: props.attributes.toggle, // here
        onChange: ( value ) => {
            props.setAttributes( { toggle: value } );
        },
    }
)

The reason why it updates the value correctly although it is not displaying it correctly is because the component ToggleControl is using a state which is outside of the component. This state, which is represented by attributes + setAttributes, is being correctly updated using setAttributes. However, it is not being correctly displayed as the prop checked is not showing the update value. This means that checked will use its default value which seems to be false.

Leave a Comment