Skip to content

Bug: useId() is not valid when used as selector in e.g. Element.closest('#' + id) #25486

Description

@lensbart

Perhaps not a bug in the true sense of the word, more a quality-of-life issue.

React version: latest (18.2.0)

Steps To Reproduce

import{useCallback,useId}from'react'constisElement=(e: EventTarget|null): e is Element=>einstanceofElementexportconstComponent=()=>{constid=useId()useEffect(()=>{consthandleClick=({ target }: MouseEvent)=>{if(isElement(target)&&target.closest(`#${id}`)==null){// do something}}document.addEventListener('click',handleClick)return()=>{document.removeEventListener('click',handleClick)}},[id])return<divid={id}/>}

The current behavior

  • Safari: SyntaxError: The string did not match the expected pattern.
  • Firefox: Uncaught DOMException: Element.closest: '#:r11:' is not a valid selector
  • Chrome: Uncaught DOMException: Failed to execute 'closest' on 'Element': '#:r11:' is not a valid selector.

This error is not thrown when using an alphanumeric id such as #watskeburt

The expected behavior

The return value of useId being directly usable in Element.closest(`#${id}`)

Workaround

target.closest(`#${id.replace(/:/g,'\\:')}`)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Status: UnconfirmedA potential issue that we haven't yet confirmed as a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions