Gutenberg programmatically move block to position

You can use getBlockRootClientId() from the block editor’s data store. E.g.

wp.data.select( 'core/block-editor' ).getBlockRootClientId( clientId )

And here’s a working example for you to see how it can be used in an edit() function, where my block contains a demo button which will move the block to the very last or first position:

  • WordPress dependencies:

    import { useBlockProps } from '@wordpress/block-editor';
    import { useSelect, useDispatch } from '@wordpress/data';
    import { Button } from '@wordpress/components';
    
  • The edit() function:

    function edit( { clientId } ) {
        const {
            getBlockRootClientId,
            getBlockIndex,
            getBlocks,
        } = useSelect( 'core/block-editor' );
    
        const { moveBlockToPosition } = useDispatch( 'core/block-editor' );
    
        // Demo callback which moves this block to the very last or first position.
        function demoMoveBlock() {
            const blocks = getBlocks();
            if ( blocks.length < 2 ) {
                alert( 'Stop playing now; there\'s only this block in the editor!' );
                return;
            }
    
            // Use the last block as the target, or the first one if this was the last block.
            let targetBlock = blocks.pop();
            if ( clientId === targetBlock.clientId ) {
                targetBlock = blocks.shift();
            }
    
            const sourceClientId   = clientId;
            const targetClientId   = targetBlock.clientId;
            const fromRootClientId = getBlockRootClientId( sourceClientId );
            const toRootClientId   = getBlockRootClientId( targetClientId );
            const targetIndex      = getBlockIndex( targetClientId );
    
            moveBlockToPosition( sourceClientId, fromRootClientId, toRootClientId, targetIndex );
        }
    
        return (
            <div { ...useBlockProps( { style: {
                backgroundColor: 'pink',
                padding: '10px',
            } } ) }>
                <Button
                    text="Move this block"
                    variant="primary"
                    onClick={ demoMoveBlock }
                />
            </div>
        );
    }