Skip to content

Instantly share code, notes, and snippets.

@codetot
Last active October 27, 2021 07:15
Show Gist options
  • Save codetot/f0d2d2833d107b4847b88ec1e6921c28 to your computer and use it in GitHub Desktop.
Save codetot/f0d2d2833d107b4847b88ec1e6921c28 to your computer and use it in GitHub Desktop.
WP Custom Block Explain
// edit.js
import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { TextControl, TextareaControl, PanelBody, ToggleControl } from '@wordpress/components';
import { useState, useEffect } from '@wordpress/element';
import './editor.scss';


export default function Edit({ attributes, setAttributes }) {
	const [displayIcon, setDislayIcon] = useState(false);
	const [darkTheme, setDarkTheme] = useState(false);

	useEffect(() => {
		if (attributes.displayIcon) {
			setDislayIcon(true);
		}

		if (attributes.isDarkTheme) {
			setDarkTheme(true);
		}
	}, [attributes]);

	const updateDisplayIcon = () => {
		setDislayIcon(!displayIcon);
		setAttributes({ displayIcon: !displayIcon });
	}

	const updateDarkTheme = () => {
		setDarkTheme(!darkTheme); // It will visible instant when toggleControl has changed
		setAttributes({ isDarkTheme: !darkTheme }); // Important: setAttributes to save it.
	}

	return (
		<div { ...useBlockProps() }>
		<!-- InsepctorControls will display a block setting in right side panel -->
			<InspectorControls>
				<PanelBody title={__('Block Settings', 'ct-blocks')}>
					<ToggleControl label={__('Display Copy Source Icon', 'ct-bones')} checked={displayIcon} onChange={updateDisplayIcon} />
					<ToggleControl label={__('Enable Dark Theme', 'ct-bones')} checked={darkTheme} onChange={updateDarkTheme} />
				</PanelBody>
			</InspectorControls>
			<TextControl label={__('Title', 'ct-blocks')} value={attributes.title} onChange={ ( value ) => setAttributes( { title: value } ) } />
			<TextareaControl label={__('Code', 'ct-blocks')} value={attributes.code} onChange={ ( value ) => setAttributes( { code: value } ) } />
		</div>
	);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment