Skip to content

Passing an object with a custom toString() as a 'class' attribute #401

@BenoitZugmeyer

Description

@BenoitZugmeyer

I am writing a library using objects with a custom toString() method to render class names. Simplified example:

const object = {
  toString() {
    return computeClassNames();
  },
  //  ... other data
};

element.className = object;

It works great on plain DOM and React, but can't work with Preact because if a class attribute is an object, it will use the object enumerable keys associated with a truthy value to format the classname.

I understand why you chose to do this, and I find it quite useful. But would you consider changing the condition to format the class objects to something like:

if (lastSimple && lastSimple.toString === Object.prototype.toString) {
    attributes.class = hashToClassName(lastSimple);
}

or (might be more robust)

if (lastSimple && String(lastSimple) === '[object Object]') {
    attributes.class = hashToClassName(lastSimple);
}

or (not the cleanest but might be more efficient)

if (lastSimple && Object.prototype.toString.call(lastSimple) === '[object Object]') {
    attributes.class = hashToClassName(lastSimple);
}

I could change my library to return an object with keys as class names, but I'd prefer not to add code specific to preact.

Thank you

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions