WordPress editor controls

Toggle Control – Coding Gutenberg block settings


Adding the toggle control to the inspector sidebar of your block

The Toggle Control is basically like a checkbox, a boolean control, or if you will, an on/off switch. It’s by far the most common control we use when building blocks. It has a boolean value, so it’s either true or false.

Form toggle control

The Toggle Control is part of the WordPress components library. Below is an example of it’s properties:

import {
    ToggleControl,
    //  FormToggle, --- same component
} from "@wordpress/components";

// or
// const { ToggleControl } = wp.components;

<ToggleControl
    label="Should text be shown?"
    help={show ? "Yes" : "No"}
    checked={show}
    onChange={() => setAttributes({ show: !show })}
/>
				

Here is a full example of how it is used inside the Inspector Controls component inside an edit function of a block:

import { InspectorControls } from "@wordpress/block-editor";
import { Fragment } from "@wordpress/element";
import {
	PanelBody,
	ToggleControl,
} from "@wordpress/components";

const edit = (props) => {
	const { className, attributes, setAttributes } = props;
	const { show } = attributes;

	return (
		<Fragment>
			<InspectorControls>
				<PanelBody title="Settings" initialOpen={false}>
					<ToggleControl
						label="Should text be shown?"
						help={show ? "Yes" : "No"}
						checked={show}
						onChange={() => setAttributes({ show: !show })}
					/>
				</PanelBody>
			</InspectorControls>
			<div>
				My Block Content
			</div>
		</Fragment>
	);
};


Read more tutorials

Stay updated with the latest from WpBlockz

* indicates required