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.
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)}`)
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>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With