I make a Gutenberg block based on React and I have a code:
import { __ } from '@wordpress/i18n';
import {
useBlockProps,
BlockControls,
AlignmentToolbar,
RichText,
InspectorControls,
} from '@wordpress/block-editor';
import { PanelBody, ToggleControl } from '@wordpress/components';
import './editor.scss';
import classnames from 'classnames';
function ButtonEdit(props) {
const { attributes, setAttributes } = props;
const { url, text, title, textAlignment, gbButtonWidth } = attributes;
const setButtonText = (newText) => {
setAttributes({ text: newText });
};
const onChangeButtonAlignment = (newAlignment) => {
setAttributes({ textAlignment: newAlignment });
};
const alignClasses = classnames(`gb-button-align-${textAlignment}`);
return (
<>
<BlockControls>
<AlignmentToolbar
value={textAlignment}
onChange={onChangeButtonAlignment}
/>
</BlockControls>
<InspectorControls>
<PanelBody title={__('Button Settings', 'gb-button')}>
<ToggleControl
label={__('Change button width', 'gb-button')}
className="toggleImage"
help={
gbButtonWidth
? __('Width 100%', 'gb-button')
: __('Default width', 'gb-button')
}
onChange={(boolean) => {
setAttributes({ gbButtonWidth: boolean });
}}
checked={gbButtonWidth}
/>
</PanelBody>
</InspectorControls>
<div
{...useBlockProps({
className: alignClasses,
})}
>
<>
<div className="wp-block-multiple-blocks-gb-button__wrapper">
<div className={`wp-block-multiple-blocks-gb-button__btn ${gbButtonWidth} full-width`}>
<RichText
className="wp-block-multiple-blocks-gb-button__btn-text"
href={url}
aria-label={__('Button text', 'gb-button')}
placeholder={__('Add text…', 'gb-button')}
title={title}
value={text}
onChange={(value) => setButtonText(value)}
identifier="text"
/>
</div>
</div>
</>
</div>
</>
);
}
export default ButtonEdit;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I have a variable "gbButtonWidth" which is responsible for toggle and changing the true/false condition.
Here, when you click on toggle, when true should add to this class:
`wp-block-multiple-blocks-gb-button__btn`
extra class:
`full-width`
and remove it if you click on toggle and false is triggered.
The toggle is done, true/false works.
I only have a problem with adding an extra class to the current class by checking $variable
2
Answers
you can add an argument (variable value) in the handleClick function
and
based on its value you can add/remove class