# Component
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'
# Properties
typeString (opens new window)? Component type, eg.text,image,video, etc.tagNameString (opens new window)? HTML tag of the component, eg.span. Default:divattributesObject (opens new window)? Key-value object of the component's attributes, eg.{ title: 'Hello' }Default:{}nameString (opens new window)? Name of the component. Will be used, for example, in Layers and badgesremovableBoolean (opens new window)? Whentruethe component is removable from the canvas, default:truedraggable(Boolean (opens new window) | String (opens new window) | Function (opens new window))? 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 containingsome-classclass andHellotitle, andcolumncomponents. 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 (opens new window) | String (opens new window) | Function (opens new window))? Indicates if it's possible to drop other components inside. You can use a query string as withdraggable. 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:truebadgableBoolean (opens new window)? Set to false if you don't want to see the badge (with the name) over the component. Default:truestylable(Boolean (opens new window) | Array (opens new window)<String (opens new window)>)? 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-requireArray (opens new window)<String (opens new window)>? Indicate an array of style properties to show up which has been marked astoRequire. Default:[]unstylableArray (opens new window)<String (opens new window)>? Indicate an array of style properties which should be hidden from the style manager. Default:[]highlightableBoolean (opens new window)? It can be highlighted with 'dotted' borders if true. Default:truecopyableBoolean (opens new window)? True if it's possible to clone the component. Default:trueresizableBoolean (opens new window)? Indicates if it's possible to resize the component. It's also possible to pass an object as options for the Resizer (opens new window). Default:falseeditableBoolean (opens new window)? Allow to edit the content of the component (used on Text components). Default:falselayerableBoolean (opens new window)? Set tofalseif you need to hide the component inside Layers. Default:trueselectableBoolean (opens new window)? Allow component to be selected when clicked. Default:truehoverableBoolean (opens new window)? Shows a highlight outline when hovering on the element iftrue. Default:truelockedBoolean (opens new window)? Disable the selection of the component and its children in the canvas. You can unlock a children by setting its locked property tofalse. Default:undefinedvoidBoolean (opens new window)? This property is used by the HTML exporter as void elements don't have closing tags, eg.<br/>,<hr/>, etc. Default:falsestyleObject (opens new window)? Component default style, eg.{ width: '100px', height: '100px', 'background-color': 'red' }stylesString (opens new window)? Component related styles, eg..my-component-class { color: red }contentString (opens new window)? Content of the component (not escaped) which will be appended before children rendering. Default:''iconString (opens new window)? Component's icon, this string will be inserted before the name (in Layers and badge), eg. it can be an HTML string ''. Default:''script(String (opens new window) | Function (opens new window))? Component's javascript. More about it here. Default:''script-export(String (opens new window) | Function (opens new window))? You can specify javascript available only in export functions (eg. when you get the HTML). If this property is defined it will overwrite thescriptone (in export functions). Default:''traitsArray (opens new window)<(Object (opens new window) | String (opens new window))>? Component's traits. More about it here. Default:['id', 'title']propagateArray (opens new window)<String (opens new window)>? 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 thepropagatearray (and thepropagateproperty itself). Default:[]toolbarArray (opens new window)<Object (opens new window)>? 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, whentoolbarproperty is falsy the editor will add automatically commandscore:component-exit(select parent component, added if there is one),tlb-move(added ifdraggable) ,tlb-clone(added ifcopyable),tlb-delete(added ifremovable).componentsCollection<Component>? Children components. Default:nulldelegateObject (opens new window)? Delegate commands to other components. Available commandsremove|move|copy|select. eg.{ remove: (cmp) => cmp.closestType('other-type') }
# init
Hook method, called once the model is created
# updated
Hook method, called when the model has been updated (eg. updated some model's property)
# Parameters
propertyString (opens new window) Property name, if triggered after some property updatevalueany Property value, if triggered after some property updatepreviousany Property previous value, if triggered after some property update
# removed
Hook method, called once the model has been removed
# is
Check component's type
# Parameters
typestring (opens new window) Component type
# Examples
component.is('image')
// -> false
Returns Boolean (opens new window)
# props
Return all the propeties
Returns Object (opens new window)
# index
Get the index of the component in the parent collection.
Returns Number (opens new window)
# setDragMode
Change the drag mode of the component. To get more about this feature read: https://github.com/GrapesJS/grapesjs/issues/1936 (opens new window)
# Parameters
valueString (opens new window) Drag mode, options:'absolute'|'translate'|''
Returns this
# getDragMode
Get the drag mode of the component.
Returns String (opens new window) Drag mode value, options: 'absolute' | 'translate' | ''
# setSymbolOverride
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.
# Parameters
value(Boolean (opens new window) | String (opens new window) | Array (opens new window)<String (opens new window)>)optionsDynamicWatchersOptions (optional, default{})
# Examples
component.setSymbolOverride(['children', 'classes']);
# getSymbolOverride
Get symbol override value.
Returns (Boolean (opens new window) | Array (opens new window)<String (opens new window)>)
# find
Find inner components by query string. ATTENTION: this method works only with already rendered component
# Parameters
queryString (opens new window) Query string
# Examples
component.find('div > .class');
// -> [Component, Component, ...]
Returns Array (opens new window) Array of components
# findType
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
# Parameters
typeString (opens new window) Component type
# Examples
const allImages = component.findType('image');
console.log(allImages[0]) // prints the first found component
Returns Array (opens new window)<Component>
# findFirstType
Find the first inner component by component type.
If no component is found, it returns undefined.
# Parameters
typeString (opens new window) Component type
# Examples
const image = component.findFirstType('image');
if (image) {
console.log(image);
}
Returns (Component | undefined (opens new window))
# closest
Find the closest parent component by query string. ATTENTION: this method works only with already rendered component
# Parameters
querystring (opens new window) Query string
# Examples
component.closest('div.some-class');
// -> Component
Returns Component
# closestType
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
# Parameters
typeString (opens new window) Component type
# Examples
const Section = component.closestType('section');
console.log(Section);
Returns Component Found component, otherwise undefined
# contains
The method returns a Boolean value indicating whether the passed component is a descendant of a given component
# Parameters
componentComponent Component to check
Returns Boolean (opens new window)
# replaceWith
Replace a component with another one
# Parameters
el(String (opens new window) | Component) Component or HTML stringoptsObject (opens new window) Options for the append action (optional, default{})
# Examples
const result = component.replaceWith('<div>Some new content</div>');
// result -> [Component]
Returns Array (opens new window)<Component> New replaced components
# setAttributes
Update attributes of the component
# Parameters
attrsObject (opens new window) Key value attributesoptsSetAttrOptions (optional, default{skipWatcherUpdates:false,fromDataSource:false})optionsObject (opens new window) Options for the model update
# Examples
component.setAttributes({ id: 'test', 'data-key': 'value' });
Returns this
# addAttributes
Add attributes to the component
# Parameters
attrsObject (opens new window) Key value attributesoptsSetAttrOptions (optional, default{})optionsObject (opens new window) Options for the model update
# Examples
component.addAttributes({ 'data-key': 'value' });
Returns this
# removeAttributes
Remove attributes from the component
# Parameters
attrs(String (opens new window) | Array (opens new window)<String (opens new window)>) Array of attributes to remove (optional, default[])optsSetOptions (optional, default{})optionsObject (opens new window) Options for the model update
# Examples
component.removeAttributes('some-attr');
component.removeAttributes(['some-attr1', 'some-attr2']);
Returns this
# getStyle
Get the style of the component
# Parameters
optionsany (optional, default{})optsAddany (optional, default{})
Returns Object (opens new window)
# setStyle
Set the style on the component
# Parameters
propObject (opens new window) Key value style object (optional, default{})optsUpdateStyleOptions (optional, default{})
# Examples
component.setStyle({ color: 'red' });
Returns Object (opens new window)
# getAttributes
Return all component's attributes
# Parameters
opts{noClass: boolean (opens new window)?, noStyle: boolean (opens new window)?} (optional, default{})
Returns Object (opens new window)
# addClass
Add classes
# Parameters
classes(Array (opens new window)<String (opens new window)> | String (opens new window)) Array or string of classes
# Examples
model.addClass('class1');
model.addClass('class1 class2');
model.addClass(['class1', 'class2']);
// -> [SelectorObject, ...]
Returns Array (opens new window) Array of added selectors
# setClass
Set classes (resets current collection)
# Parameters
classes(Array (opens new window)<String (opens new window)> | String (opens new window)) Array or string of classes
# Examples
model.setClass('class1');
model.setClass('class1 class2');
model.setClass(['class1', 'class2']);
// -> [SelectorObject, ...]
Returns Array (opens new window) Array of added selectors
# removeClass
Remove classes
# Parameters
classes(Array (opens new window)<String (opens new window)> | String (opens new window)) Array or string of classes
# Examples
model.removeClass('class1');
model.removeClass('class1 class2');
model.removeClass(['class1', 'class2']);
// -> [SelectorObject, ...]
Returns Array (opens new window) Array of removed selectors
# getClasses
Returns component's classes as an array of strings
Returns Array (opens new window)
# append
Add new component children
# Parameters
components(Component | String (opens new window)) Component to addoptsObject (opens new window) Options for the append action (optional, default{})
# Examples
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 (opens new window) Array of appended components
# components
Set new collection if components are provided, otherwise the
current collection is returned
# Parameters
components(Component | Array (opens new window)<Component> | String (opens new window))? Component Definitions or HTML stringoptsObject (opens new window) Options, same as inComponent.append()(optional, default{})
# Examples
// Set new collection
component.components('<span></span><div></div>');
// Get current collection
const collection = component.components();
console.log(collection.length);
// -> 2
Returns (Collection | Array (opens new window)<Component>)
# getChildAt
If exists, returns the child component at specific index.
# Parameters
indexNumber (opens new window) Index of the component to return
# Examples
// Return first child
component.getChildAt(0);
// Return second child
component.getChildAt(1);
Returns (Component | null)
# getLastChild
If exists, returns the last child component.
# Examples
const lastChild = component.getLastChild();
Returns (Component | null)
# empty
Remove all inner components
- @return {this}
# Parameters
opts(optional, default{})
# parent
Get the parent component, if exists
# Parameters
optsany (optional, default{})
# Examples
component.parent();
// -> Component
Returns (Component | null)
# parents
Return all parents of the component.
Returns Array (opens new window)<Component>
# getTraits
Get traits.
# Examples
const traits = component.getTraits();
console.log(traits);
// [Trait, Trait, Trait, ...]
Returns Array (opens new window)<Trait>
# setTraits
Replace current collection of traits with a new one.
# Parameters
traitsArray (opens new window)<Object (opens new window)> Array of trait definitions
# Examples
const traits = component.setTraits([{ type: 'checkbox', name: 'disabled'}, ...]);
console.log(traits);
// [Trait, ...]
Returns Array (opens new window)<Trait>
# getTrait
Get the trait by id/name.
# Parameters
idString (opens new window) Theidornameof the trait
# Examples
const traitTitle = component.getTrait('title');
traitTitle && traitTitle.set('label', 'New label');
Returns (Trait | null) Trait getModelToStyle
# updateTrait
Update a trait.
# Parameters
idString (opens new window) Theidornameof the traitpropsObject (opens new window) Object with the props to update
# Examples
component.updateTrait('title', {
type: 'select',
options: [ 'Option 1', 'Option 2' ],
});
Returns this
# getTraitIndex
Get the trait position index by id/name. Useful in case you want to replace some trait, at runtime, with something else.
# Parameters
idString (opens new window) Theidornameof the trait
# Examples
const traitTitle = component.getTraitIndex('title');
console.log(traitTitle); // 1
Returns Number (opens new window) Index position of the current trait
# removeTrait
Remove trait/s by id/s.
# Parameters
id(String (opens new window) | Array (opens new window)<String (opens new window)>) Theid/nameof the trait (or an array)
# Examples
component.removeTrait('title');
component.removeTrait(['title', 'id']);
Returns Array (opens new window)<Trait> Array of removed traits
# addTrait
Add new trait/s.
# Parameters
trait(String (opens new window) | Object (opens new window) | Array (opens new window)<(String (opens new window) | Object (opens new window))>) Trait to add (or an array of traits)optsOptions Options for the add (optional, default{})
# Examples
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 (opens new window)<Trait> Array of added traits
# getName
Get the name of the component.
# Parameters
optsObject (opens new window) Options (optional, default{})opts.noCustomBoolean (opens new window)? Avoid custom name assigned to the component.
Returns String (opens new window)
# setName
Update component name.
# Parameters
nameString (opens new window) New name.optsSetOptions (optional, default{})
# getIcon
Get the icon string
Returns String (opens new window)
# toHTML
Return HTML string of the component
# Parameters
optsObject (opens new window) Options (optional, default{})opts.tagString (opens new window)? Custom tagNameopts.attributes(Object (opens new window) | Function (opens new window)) 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, defaultnull)opts.withPropsBoolean (opens new window)? Include component properties asdata-gjs-*attributes. This allows you to have re-importable HTML.opts.altQuoteAttrBoolean (opens new window)? In case the attribute value contains a"char, instead of escaping it (attr="value ""), the attribute will be quoted using single quotes (attr='value "').
# Examples
// 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 (opens new window) HTML string
# getInnerHTML
Get inner HTML of the component
# Parameters
optsObject (opens new window) Same options oftoHTML(optional, default{})
Returns String (opens new window) HTML string
# getChangedProps
Return an object containing only changed props
# Parameters
resPartial<ComponentDefinition>
Returns Partial<ComponentDefinition>
# getId
Return the component id
Returns String (opens new window)
# setId
Set new id on the component
# Parameters
idString (opens new window)optsany?
Returns this
# getEl
Get the DOM element of the component. This works only if the component is already rendered
# Parameters
frameFrame Specific frame from which taking the element
Returns HTMLElement (opens new window)
# getView
Get the View of the component. This works only if the component is already rendered
# Parameters
frameFrame Get View of a specific frame
Returns ComponentView
# onAll
Execute callback function on itself and all inner components
# Parameters
clbFunction (opens new window) Callback function, the model is passed as an argument
# Examples
component.onAll(component => {
// do something with component
})
Returns this
# forEachChild
Execute a callback function on all inner child components.
# Parameters
clbFunction (opens new window) Callback function, the child component is passed as an argument
# Examples
component.forEachChild(child => {
console.log(child)
})
# remove
Remove the component
# Parameters
optsany (optional, default{})
Returns this
# move
Move the component to another destination component
# Parameters
componentComponent Destination component (so the current one will be appended as a child)optsObject (opens new window) Options for the append action (optional, default{})
# Examples
// Move the selected component on top of the wrapper
const dest = editor.getWrapper();
editor.getSelected().move(dest, { at: 0 });
Returns this
# isInstanceOf
Check if the component is an instance of some component type.
# Parameters
typeString (opens new window) Component type
# Examples
// 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 (opens new window)
# isChildOf
Check if the component is a child of some other component (or component type)
# Parameters
component(Component | String (opens new window)) Component parent to check. In case a string is passed, the check will be performed on the component type.
# Examples
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 (opens new window)
← DOM Components Panels →