Issue #3170Opened December 7, 2020by ThetripGr0 reactions

Add class name from traits

Question

Hello, what i am trying to achieve is to have the text component extended by assigning an extra trait named Alignment and deciding through the trait the kind of alignment i wish to do, after that no css should be applied but the appropriate class name should be given to the component. Is there an example of how i could do something like that, i couldn't find something on my own :/ ?

Answers (2)

ThetripGrDecember 7, 20200 reactions

So i got it working after some more tries, i will try to explain how i got it to work. When you define the trait

defaults: {
       traits: [{type: 'select',
		options: [{
                   { value: 'myCustomClass', name: 'Option A' },
                }],
		label: 'traitLabel',
		name: 'traitName',
		changeProp: 1
        }]
},

you can declare a name. When you select option A from the dropdown selection you can track this change on init(), as this.on('change:traitName', this.handleChange);, then all you have to do is write down the handleChange function to do whatever you want it to do. Below i paste the code for how i handled adding/replacing a class.

handleChange(props) {
	var classes = this.getAttributes().class,
		newClass = props.changed.traitName,
		arClasses = classes.split(" ");
	var filter = arClasses.filter(function (el) {
		if (['myGivenClass'].includes(el))
			return el;
	});
	if (filter.length != 0) {
		this.removeClass(filter);
		classes = this.getAttributes().class
	}
	this.setClass(classes + " " + newClass)
},

sry for the formatting but i do not know how to paste formatted code yet :P

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...

Browse Plugin Categories

Jump directly to plugin category pages on the marketplace.