Issue #494💬 AnsweredOpened November 8, 2017by z-vr0 reactions

Place block as component programmatically

Quick answerby z-vr

Oh I found out how to do it -- via editor.addComponents({ type: 'MyComponent' }). Is there a way to insert it into a specific element by a CSS selector? Found this snippet, but how would i find the correct index?

Read full answer below ↓

Question

I've created a custom type, and a block

DomComponents.addType('MyComponent', { ... });
BlockManager.add('Component', { content: { type: 'MyComponent' } });

is it possible to insert it into DomComponents by name or any other means? I don't want to be drag'n'dropping the block manually each time. Thanks.

Answers (3)

z-vrNovember 8, 2017

Oh I found out how to do it -- via editor.addComponents({ type: 'MyComponent' }). Is there a way to insert it into a specific element by a CSS selector?

Found this snippet, but how would i find the correct index?

editor.getComponents().add('<div>Text</div>', {at: index});
z-vrNovember 8, 2017

ok so what i've done is and then I think traversing the model tree would be a very good feature -- I'll work on the PR at some point. Cheers!

artfNovember 8, 2017

You can actually get the model from the cash element instance with view.$el.data('model'), so you might make it work with less code

wrapper.view.$el.find('#hero .text').each((el, i, $el) => 
    console.log($el.data('model'))
)

Related Questions and Answers

Continue research with similar issue discussions.

Paid Plugins That Match This Issue

Curated by issue keywords and label relevance to help you ship faster.

View all plugins

Loading paid plugin recommendations...

Free option

Check the open-source GrapesJS plugins on GitHub or run a quick search in our free catalog.

Browse free plugins →
Premium option

Premium plugins ship with support, regular updates, and production-ready features — save days of integration work.

Browse premium plugins →

Related tutorials

In-depth guides on the same topic.

All tutorials →

Browse Plugin Categories

Jump directly to plugin category pages on the marketplace.