Bug: `useId()` is not valid when used as selector in e.g. `Element.closest('#' + id)`
See original GitHub issuePerhaps 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'
const isElement = (e: EventTarget | null): e is Element => e instanceof Element
export const Component = () => {
const id = useId()
useEffect(() => {
const handleClick = ({ target }: MouseEvent) => {
if (isElement(target) && target.closest(`#${id}`) == null) {
// do something
}
}
document.addEventListener('click', handleClick)
return () => {
document.removeEventListener('click', handleClick)
}
}, [id])
return <div id={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, '\\:')}`)
Issue Analytics
- State:
- Created a year ago
- Comments:5 (2 by maintainers)
Top Results From Across the Web
React useId creates invalid selector - Stack Overflow
I used Element.closest which accepts string selector. .closest method works the same way as the querySelector , so I simplified the question.
Read more >Element.closest() - Web APIs - MDN Web Docs
A string of valid CSS selector to match the Element and its ancestors against. Return value. The closest ancestor Element or itself, which ......
Read more >Practical Use Cases for JavaScript's closest() Method
Element.closest() allows us to traverse up the DOM until we get an element that matches the given selector. The awesomeness is that we...
Read more >Hooks API Reference - React
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. This page...
Read more >The React Handbook – Learn React for Beginners
This book does not try to cover everything under the sun related to ... The rest element is useful when working with array...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I was thinking you’d do
ref.current.contains(e.target)
to check.Node.contains()
— you learn something new every day!