Skip to content

Instantly share code, notes, and snippets.

@ryanwelcher
Created October 12, 2023 18:24
Show Gist options
  • Save ryanwelcher/ca348876f2f02a051166e7c56d2dad69 to your computer and use it in GitHub Desktop.
Save ryanwelcher/ca348876f2f02a051166e7c56d2dad69 to your computer and use it in GitHub Desktop.
Using the useBlockEditingMode hook
/**
* WordPress Dependencies
*/
import {
useBlockProps,
useBlockEditingMode,
RichText,
store as blockEditorStore,
} from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';
/**
* Internal Dependencies
*/
import './editor.scss';
export default function Edit( {
attributes: { message },
setAttributes,
clientId,
} ) {
const { blocks, getBlockIndex, getBlockParents } = useSelect(
( select ) => {
return {
blocks: select( blockEditorStore ).getBlocks(),
getBlockIndex: select( blockEditorStore ).getBlockIndex,
getBlockOrder: select( blockEditorStore ).getBlockOrder,
getBlockParents: select( blockEditorStore ).getBlockParents,
};
},
[]
);
let mode = 'default';
if ( getBlockParents( clientId ).length ) {
mode = 'contentOnly';
} else {
const index = getBlockIndex( clientId );
if ( index > 0 ) {
if ( blocks[ index - 1 ].name === 'core/paragraph' ) {
mode = 'disabled';
}
}
}
// Possible values: 'disabled', 'contentOnly', and 'default'
useBlockEditingMode( mode );
return (
<RichText
{ ...useBlockProps() }
tagName="p"
value={ message }
onChange={ ( newMessage ) =>
setAttributes( { message: newMessage } )
}
/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment