Created
October 12, 2023 18:24
-
-
Save ryanwelcher/ca348876f2f02a051166e7c56d2dad69 to your computer and use it in GitHub Desktop.
Using the useBlockEditingMode hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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