Mithril.js multiple css classes

I am new to mithril.js. I have a div, I want to add the class "invalid" if ctrl.invalid () == true and "hidden" if ctrl.hidden () == true.

If I use m('div', {class: ctrl.invalid() ? 'invalid' : '', class: ctrl.hidden()? 'hidden' : ''}) , they override each other.

I can use m('div', {class: [ctrl.invalid()?'invalid':'', ctrl.focused()?'focused':''].join(' ')}) , and it will work, but it looks messy.

Is there an elegant solution for this? Thanks.

+5
source share
2 answers

I recommend you use classnames - a simple utility for this. You can easily define your classes and combine everything for you. In your case, it will be:

 const myMergedClasses = classNames({ invalid: ctrl.invalid(), focused: ctrl.focused() }); m('div', { class: myMergedClasses }) 

Beautiful ?!

+4
source

You can add a helper method to your Mithril component:

 const myComponent = { css() { // Add some logic return 'class1 class2'; }, view() { return m('div', { class: this.css() }); }, }; 

Or to the controller:

 const ctrl = { css() { // Add some logic return 'class3'; }, }; const myComponent = { view() { return m('div', { class: ctrl.css() }); }, }; 

Choose the one that best suits your business.

You can also use the classnames utility, as Ross Hanas suggested in his answer:

 const myComponent = { css() { return classNames({ invalid: ctrl.invalid(), focused: ctrl.focused(), }); }, view() { return m('div', { class: this.css() }); }, }; 

Or:

 const ctrl = { css() { return classNames({ invalid: this.invalid(), focused: this.focused(), }); }, invalid() { /* ... */ }, focused() { /* ... */ }, }; const myComponent = { view() { return m('div', { class: ctrl.css() }); }, }; 
0
source

Source: https://habr.com/ru/post/1246788/


All Articles