redom / redom

Tiny (2 KB) turboboosted JavaScript library for creating user interfaces.

Home Page:https://redom.js.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

readonly attribute

data-handler opened this issue · comments

commented

I'm not sure if this is an issue / bug but the readonly attribute seems to be treated differently to the disabled attribute when creating input elements with redom.

e.g.

el('input', {
    type: 'text',
    readonly: false,
    disabled: false
});

renders

<input type="text" readonly="false">

The disabled attribute is omitted but the readonly attribute is added.

Should the readonly attribute be omitted also, when set to "false"?

Some HTML properties are rendered as attributes as well and some not, it's just how DOM works.. For example when you set input value property value, it's not rendered as attribute..

commented

That makes sense. Would be nice not to have to deal with that ‘manually’, though.

E.g. I’m using spread to conditionally include / exclude readonly attribute:

function createInputAttributes(options) {
    return {
            disabled: options.disabled,
            …(options.readonly && { readonly: true })
            };
}

You could try:

function createInputAttributes (options) {
  const { readonly, disabled } = options;
  
  return {
    disabled,
    readonly: readonly ? '' : undefined
  }
}

or:

function createInputAttributes (options) {
  const { readonly, disabled } = options;
  
  return {
    disabled,
    readonly: attr(readonly)
  }
}

function attr (value) {
  return value ? '' : undefined;
}
commented

Yes, thanks. Just meant it would be nice if redom took care of that but I guess that means it would be doing ‘magic’ that it shouldn’t be?

You can actually also create your own "middleware", like this:

el('input', attr('readonly', options.readonly ? '' : undefined))

function attr (key, value) {
  return function (el) {
    el.setAttribute(key, value);
  }
}

That forces it to set attribute, not property.

commented

Thanks 👍

No worries, happy to help anytime! You can also do the same with properties:

el('input', prop('disabled', options.disabled))

function prop (key, value) {
  return function (el) {
    el[key] = value;
  }
}
commented

Cool. Thanks again 🙂