0

I want to get the selected block (an inner block) every time a new block is selected.

I am trying the following:

edit() {
  const selectedBlock = wp.data.select( 'core/block-editor' ).getSelectedBlock();
  
  useEffect( () => {
    console.log( selectedBlock );
  }, [ selectedBlock ] );
})

The selected block is returned only when the block renders. Nothing happens when I select a new inner block. It works only when I click out of the parent block, then click again an inner block.

1

1 Answer 1

0

In short, use the useSelect() hook or the withSelect() HOC utility from @wordpress/data to create a subscription to selected value. Either will trigger a render whenever the selected value changes in state:

import { useSelect } from '@wordpress/data';

edit() {
  const selectedBlock = useSelect(
    ( select ) => select( 'core/block-editor' ).getSelectedBlock()
  );

  useEffect( () => {
    console.log( selectedBlock );
  }, [ selectedBlock ] );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.