React useId creates invalid selector
Asked Answered
L

2

11

I am trying to get the element by id. (It's an example code to reproduce the error)

function MyComponent(){
  const myId = useId();

  useEffect(() => {
    const myComponentDOMElement = document.querySelector(`#${myId}`); // error here
    }
  )

  return <div id={ myId }> text </div>
}

This code gives an error:

Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#:Rt6m:' is not a valid selector.

useRef couldn't help me in my case. How can I use the ID to get the element.

Lajoie answered 29/9, 2022 at 10:35 Comment(3)
why would useRef couldn't help πŸ€” just curious ... – Woolfolk
Thanks for asking, TIL something new about querySelector πŸ˜‰ – Woolfolk
@Woolfolk I was making a custom Select component. To close it onClick somewhere else I was adding an event listener to document.body. To check if I clicked outside the select I was checking if event.target has a parent which is opened select. I used Element.closest which accepts string selector. .closest method works the same way as the querySelector, so I simplified the question. – Lajoie
C
22

The IDs generated by React's useId are surrounded by colons (for example :R1ab6km:) and these special characters get interpreted by querySelector. You can escape them using CSS.escape() so that querySelector treats those characters literally.

document.querySelector(`#${CSS.escape(id)}`)
Crosspollination answered 19/1, 2023 at 20:47 Comment(0)
L
6

I figured out that I can use the attribute selector.

function MyComponent(){
  const myId = useId();

  useEffect(() => {
    const myComponentDOMElement = document.querySelector(`[id="${myId}"]`); // this will work
    }
  )
  return <div id={ myId }> text </div>
}
Lajoie answered 29/9, 2022 at 10:35 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.