Gutenberg: Question: Use insertBlocks to insert into nested block

Created on 3 Oct 2018  Â·  5Comments  Â·  Source: WordPress/gutenberg

I'm trying to figure out how to add a button to a block that, when clicked, will add a new child block to a parent block.

I see I can use wp.data.dispatch('core/editor').insertBlocks(block) to add a block to the editor, but I'm not sure how to specify that it should go _inside_ a nest-able block.

I see the documentation here, but I'm unsure if the root client ID is what I need to get it to insert into a parent block, and if so, how I would go about getting that.

Thank in advance for any help!

[Feature] Nested / Inner Blocks [Type] Help Request

Most helpful comment

Hi @raquelmsmith —

Great question! I happen to have an example you can use in our custom columns block.

Quick code tour:

  • Line 46: clientId is a prop available on your block. This is the client ID of the block you want to insert into.
  • Line 151: This is our button that will fire the onAddColumn callback when clicked. (Could just be generic onClick or addBlock or whatever too.)
  • Line 56: This is our actual callback that inserts the block.

    • Line 60: This is where we create the block object that we're going to insert

    • Line 66 This is where we dispatch the insert action, with the block we just created and referencing the clientID from the block props

    • Line 69: We persist some info about the nested blocks as block attributes but you could skip that if you want.

Let me know if it helps and I can close this up!

All 5 comments

Hi @raquelmsmith —

Great question! I happen to have an example you can use in our custom columns block.

Quick code tour:

  • Line 46: clientId is a prop available on your block. This is the client ID of the block you want to insert into.
  • Line 151: This is our button that will fire the onAddColumn callback when clicked. (Could just be generic onClick or addBlock or whatever too.)
  • Line 56: This is our actual callback that inserts the block.

    • Line 60: This is where we create the block object that we're going to insert

    • Line 66 This is where we dispatch the insert action, with the block we just created and referencing the clientID from the block props

    • Line 69: We persist some info about the nested blocks as block attributes but you could skip that if you want.

Let me know if it helps and I can close this up!

Yes, that helped a bunch! Don't know how I didn't realize that clientId was a prop available on the block... 😆 Thanks so much for the help!

@raquelmsmith Woot! Glad it helped!

@chrisvanpatten
I want to test your columns block but I'm having trouble setting it up.
I build the javascript file, enqueued it but blocks don't show in Gutenberg and I get no errors.

@2one2 Sorry about that; had some small issues in the code. Just pushed up an improved version.

Was this page helpful?
0 / 5 - 0 ratings