htmlstreamofficial / preline

Preline UI is an open-source set of prebuilt UI components based on the utility-first Tailwind CSS framework.

Home Page:https://preline.co

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add support to escape ID for React's useId hook

elasticizer opened this issue · comments

Current behavior

I'm encountering a SyntaxError when using the useId hook with the data-hs-overlay attribute.

SyntaxError: Failed to execute 'querySelector' on 'Document': '#:Rm:-backdrop' is not a valid selector.

Cause

The colon (:) character in the generated ID (#::Rm:-backdrop) is causing the error. Colons have a special meaning in CSS selectors and need to be escaped when used within an ID. 1

const backdrop: HTMLElement = document.querySelector(
`#${this.overlay.id}-backdrop`,
);

Proposed solution

I propose adding support for React's useId hook while ensuring compatibility with the data-hs-overlay attribute. Here are two possible approaches: 2

  1. Attribute selector

    `[id="${this.overlay.id}-backdrop"]`

    This approach uses an attribute selector to target the element with an ID matching the generated ID from useId followed by -backdrop. This avoids the colon issue entirely.

  2. Escaped ID

    `#${CSS.escape(this.overlay.id)}-backdrop`

    This approach leverages the CSS.escape function to escape the colon in the generated ID. This ensures the ID is valid and can be used as a CSS selector.

Expected behavior

I'd like to see support for useId with data-hs-overlay implemented in a solution that addresses the colon issue effectively.

Thank you for considering this issue!

Footnotes

  1. https://stackoverflow.com/questions/73894096/react-useid-creates-invalid-selector

  2. https://stackoverflow.com/questions/45110893/select-elements-by-attributes-with-colon