docs/api/component.md
The Component object represents a single node of our template structure, so when you update its properties the changes are immediately reflected on the canvas and in the code to export (indeed, when you ask to export the code we just go through all the tree of nodes). An example on how to update properties:
component.set({
tagName: 'span',
attributes: { ... },
removable: false,
});
component.get('tagName');
// -> 'span'
type String? Component type, eg. text, image, video, etc.tagName String? HTML tag of the component, eg. span. Default: divattributes Object? Key-value object of the component's attributes, eg. { title: 'Hello' } Default: {}name String? Name of the component. Will be used, for example, in Layers and badgesremovable Boolean? When true the component is removable from the canvas, default: truedraggable (Boolean | String | Function)? Indicates if it's possible to drag the component inside others.
You can also specify a query string to identify elements,
eg. '.some-class[title=Hello], [data-gjs-type=column]' means you can drag the component only inside elements
containing some-class class and Hello title, and column components. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drag is possible. Default: truedroppable (Boolean | String | Function)? Indicates if it's possible to drop other components inside. You can use
a query string as with draggable. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drop is possible. Default: truebadgable Boolean? Set to false if you don't want to see the badge (with the name) over the component. Default: truestylable (Boolean | Array<String>)? True if it's possible to style the component.
You can also indicate an array of CSS properties which is possible to style, eg. ['color', 'width'], all other properties
will be hidden from the style manager. Default: truestylable-require Array<String>? Indicate an array of style properties to show up which has been marked as toRequire. Default: []unstylable Array<String>? Indicate an array of style properties which should be hidden from the style manager. Default: []highlightable Boolean? It can be highlighted with 'dotted' borders if true. Default: truecopyable Boolean? True if it's possible to clone the component. Default: trueresizable Boolean? Indicates if it's possible to resize the component. It's also possible to pass an object as options for the Resizer. Default: falseeditable Boolean? Allow to edit the content of the component (used on Text components). Default: falselayerable Boolean? Set to false if you need to hide the component inside Layers. Default: trueselectable Boolean? Allow component to be selected when clicked. Default: truehoverable Boolean? Shows a highlight outline when hovering on the element if true. Default: truelocked Boolean? Disable the selection of the component and its children in the canvas. You can unlock a children by setting its locked property to false. Default: undefinedvoid Boolean? This property is used by the HTML exporter as void elements don't have closing tags, eg. , <hr/>, etc. Default: falsestyle Object? Component default style, eg. { width: '100px', height: '100px', 'background-color': 'red' }styles String? Component related styles, eg. .my-component-class { color: red }content String? Content of the component (not escaped) which will be appended before children rendering. Default: ''icon String? Component's icon, this string will be inserted before the name (in Layers and badge), eg. it can be an HTML string '<i class="fa fa-square-o"></i>'. Default: ''script (String | Function)? Component's javascript. More about it here. Default: ''script-export (String | Function)? You can specify javascript available only in export functions (eg. when you get the HTML).
If this property is defined it will overwrite the script one (in export functions). Default: ''traits Array<(Object | String)>? Component's traits. More about it here. Default: ['id', 'title']propagate Array<String>? Indicates an array of properties which will be inhereted by all NEW appended children.
For example if you create a component likes this: { removable: false, draggable: false, propagate: ['removable', 'draggable'] }
and append some new component inside, the new added component will get the exact same properties indicated in the propagate array (and the propagate property itself). Default: []toolbar Array<Object>? Set an array of items to show up inside the toolbar when the component is selected (move, clone, delete).
Eg. toolbar: [ { attributes: {class: 'fa fa-arrows'}, command: 'tlb-move' }, ... ].
By default, when toolbar property is falsy the editor will add automatically commands core:component-exit (select parent component, added if there is one), tlb-move (added if draggable) , tlb-clone (added if copyable), tlb-delete (added if removable).components Collection<Component>? Children components. Default: nulldelegate Object? Delegate commands to other components. Available commands remove | move | copy | select. eg. { remove: (cmp) => cmp.closestType('other-type') }Hook method, called once the model is created
Hook method, called when the model has been updated (eg. updated some model's property)
property String Property name, if triggered after some property updatevalue any Property value, if triggered after some property updateprevious any Property previous value, if triggered after some property updateHook method, called once the model has been removed
Check component's type
type string Component typecomponent.is('image')
// -> false
Returns Boolean
Return all the propeties
Returns Object
Get the index of the component in the parent collection.
Returns Number
Change the drag mode of the component. To get more about this feature read: https://github.com/GrapesJS/grapesjs/issues/1936
value String Drag mode, options: 'absolute' | 'translate' | ''Returns this
Get the drag mode of the component.
Returns String Drag mode value, options: 'absolute' | 'translate' | ''
Set symbol override.
By setting override to true, none of its property changes will be propagated to relative symbols.
By setting override to specific properties, changes of those properties will be skipped from propagation.
component.setSymbolOverride(['children', 'classes']);
Get symbol override value.
Returns (Boolean | Array<String>)
Find inner components by query string. ATTENTION: this method works only with already rendered component
query String Query stringcomponent.find('div > .class');
// -> [Component, Component, ...]
Returns Array Array of components
Find all inner components by component type.
The advantage of this method over find is that you can use it
also before rendering the component
type String Component typeconst allImages = component.findType('image');
console.log(allImages[0]) // prints the first found component
Returns Array<Component>
Find the first inner component by component type.
If no component is found, it returns undefined.
type String Component typeconst image = component.findFirstType('image');
if (image) {
console.log(image);
}
Returns (Component | undefined)
Find the closest parent component by query string. ATTENTION: this method works only with already rendered component
query string Query stringcomponent.closest('div.some-class');
// -> Component
Returns Component
Find the closest parent component by its type.
The advantage of this method over closest is that you can use it
also before rendering the component
type String Component typeconst Section = component.closestType('section');
console.log(Section);
Returns Component Found component, otherwise undefined
The method returns a Boolean value indicating whether the passed component is a descendant of a given component
component Component Component to checkReturns Boolean
Replace a component with another one
el (String | Component) Component or HTML stringopts Object Options for the append action (optional, default {})const result = component.replaceWith('<div>Some new content</div>');
// result -> [Component]
Returns Array<Component> New replaced components
Update attributes of the component
attrs Object Key value attributesopts SetAttrOptions (optional, default {skipWatcherUpdates:false,fromDataSource:false})options Object Options for the model updatecomponent.setAttributes({ id: 'test', 'data-key': 'value' });
Returns this
Add attributes to the component
attrs Object Key value attributesopts SetAttrOptions (optional, default {})options Object Options for the model updatecomponent.addAttributes({ 'data-key': 'value' });
Returns this
Remove attributes from the component
attrs (String | Array<String>) Array of attributes to remove (optional, default [])opts SetOptions (optional, default {})options Object Options for the model updatecomponent.removeAttributes('some-attr');
component.removeAttributes(['some-attr1', 'some-attr2']);
Returns this
Get the style of the component
opts GetComponentStyleOpts? Returns Object
Set the style on the component
prop Object Key value style object (optional, default {})opts UpdateStyleOptions (optional, default {})component.setStyle({ color: 'red' });
Returns Object
Return all component's attributes
Returns Object
Add classes
model.addClass('class1');
model.addClass('class1 class2');
model.addClass(['class1', 'class2']);
// -> [SelectorObject, ...]
Returns Array Array of added selectors
Set classes (resets current collection)
model.setClass('class1');
model.setClass('class1 class2');
model.setClass(['class1', 'class2']);
// -> [SelectorObject, ...]
Returns Array Array of added selectors
Remove classes
model.removeClass('class1');
model.removeClass('class1 class2');
model.removeClass(['class1', 'class2']);
// -> [SelectorObject, ...]
Returns Array Array of removed selectors
Returns component's classes as an array of strings
Returns Array
Add new component children
components (Component | String) Component to addopts Object Options for the append action (optional, default {})someComponent.get('components').length // -> 0
const videoComponent = someComponent.append('<video></video><div></div>')[0];
// This will add 2 components (`video` and `div`) to your `someComponent`
someComponent.get('components').length // -> 2
// You can pass components directly
otherComponent.append(otherComponent2);
otherComponent.append([otherComponent3, otherComponent4]);
// append at specific index (eg. at the beginning)
someComponent.append(otherComponent, { at: 0 });
Returns Array Array of appended components
Set new collection if components are provided, otherwise the
current collection is returned
components (Component | Array<Component> | String)? Component Definitions or HTML stringopts Object Options, same as in Component.append() (optional, default {})// Set new collection
component.components('<span></span><div></div>');
// Get current collection
const collection = component.components();
console.log(collection.length);
// -> 2
Returns (Collection | Array<Component>)
If exists, returns the child component at specific index.
index Number Index of the component to return// Return first child
component.getChildAt(0);
// Return second child
component.getChildAt(1);
Returns (Component | null)
If exists, returns the last child component.
const lastChild = component.getLastChild();
Returns (Component | null)
Remove all inner components
opts (optional, default {})Get the parent component, if exists
opts any (optional, default {})component.parent();
// -> Component
Returns (Component | null)
Return all parents of the component.
Returns Array<Component>
Get traits.
const traits = component.getTraits();
console.log(traits);
// [Trait, Trait, Trait, ...]
Returns Array<Trait>
Replace current collection of traits with a new one.
const traits = component.setTraits([{ type: 'checkbox', name: 'disabled'}, ...]);
console.log(traits);
// [Trait, ...]
Returns Array<Trait>
Get the trait by id/name.
id String The id or name of the traitconst traitTitle = component.getTrait('title');
traitTitle && traitTitle.set('label', 'New label');
Returns (Trait | null) Trait getModelToStyle
Update a trait.
component.updateTrait('title', {
type: 'select',
options: [ 'Option 1', 'Option 2' ],
});
Returns this
Get the trait position index by id/name. Useful in case you want to replace some trait, at runtime, with something else.
id String The id or name of the traitconst traitTitle = component.getTraitIndex('title');
console.log(traitTitle); // 1
Returns Number Index position of the current trait
Remove trait/s by id/s.
component.removeTrait('title');
component.removeTrait(['title', 'id']);
Returns Array<Trait> Array of removed traits
Add new trait/s.
trait (String | Object | Array<(String | Object)>) Trait to add (or an array of traits)opts Options Options for the add (optional, default {})component.addTrait('title', { at: 1 }); // Add title trait (`at` option is the position index)
component.addTrait({
type: 'checkbox',
name: 'disabled',
});
component.addTrait(['title', {...}, ...]);
Returns Array<Trait> Array of added traits
Get the name of the component.
opts Object Options (optional, default {})
opts.noCustom Boolean? Avoid custom name assigned to the component.Returns String
Update component name.
name String New name.opts SetOptions (optional, default {})Get the icon string
Returns String
Return HTML string of the component
opts Object Options (optional, default {})
opts.tag String? Custom tagNameopts.attributes (Object | Function) You can pass an object of custom attributes to replace with the current ones or you can even pass a function to generate attributes dynamically. (optional, default null)opts.withProps Boolean? Include component properties as data-gjs-* attributes. This allows you to have re-importable HTML.opts.altQuoteAttr Boolean? In case the attribute value contains a " char, instead of escaping it (attr="value ""), the attribute will be quoted using single quotes (attr='value "').// Simple HTML return
component.set({ tagName: 'span' });
component.setAttributes({ title: 'Hello' });
component.toHTML();
// -> <span title="Hello"></span>
// Custom attributes
component.toHTML({ attributes: { 'data-test': 'Hello' } });
// -> <span data-test="Hello"></span>
// Custom dynamic attributes
component.toHTML({
attributes(component, attributes) {
if (component.get('tagName') == 'span') {
attributes.title = 'Custom attribute';
}
return attributes;
},
});
// -> <span title="Custom attribute"></span>
Returns String HTML string
Get inner HTML of the component
opts Object Same options of toHTML (optional, default {})Returns String HTML string
Return an object containing only changed props
res Partial<ComponentDefinition> Returns Partial<ComponentDefinition>
Return the component id
Returns String
Set new id on the component
id String opts any? Returns this
Get the DOM element of the component. This works only if the component is already rendered
frame Frame Specific frame from which taking the elementReturns HTMLElement
Get the View of the component. This works only if the component is already rendered
frame Frame Get View of a specific frameReturns ComponentView
Execute callback function on itself and all inner components
clb Function Callback function, the model is passed as an argumentcomponent.onAll(component => {
// do something with component
})
Returns this
Execute a callback function on all inner child components.
clb Function Callback function, the child component is passed as an argumentcomponent.forEachChild(child => {
console.log(child)
})
Remove the component
opts any (optional, default {})Returns this
Move the component to another destination component
component Component Destination component (so the current one will be appended as a child)opts Object Options for the append action (optional, default {})// Move the selected component on top of the wrapper
const dest = editor.getWrapper();
editor.getSelected().move(dest, { at: 0 });
Returns this
Check if the component is an instance of some component type.
type String Component type// Add a new component type by extending an existing one
editor.Components.addType('text-ext', { extend: 'text' });
// Append a new component somewhere
const newTextExt = editor.getSelected().append({ type: 'text-ext' })[0];
newTextExt.isInstanceOf('text-ext'); // true
newTextExt.isInstanceOf('text'); // true
Returns Boolean
Check if the component is a child of some other component (or component type)
component (Component | String) Component parent to check. In case a string is passed,
the check will be performed on the component type.const newTextComponent = editor.getSelected().append({
type: 'text',
components: 'My text <b>here</b>',
})[0];
const innerComponent = newTextComponent.find('b')[0];
innerComponent.isChildOf(newTextComponent); // true
innerComponent.isChildOf('text'); // true
Returns Boolean