Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useId creates invalid selector

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.

like image 664
Yevhenii Shlapak Avatar asked Nov 19 '25 10:11

Yevhenii Shlapak


2 Answers

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)}`)
like image 115
Etienne Martin Avatar answered Nov 22 '25 00:11

Etienne Martin


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>
}
like image 20
Yevhenii Shlapak Avatar answered Nov 21 '25 22:11

Yevhenii Shlapak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!