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.
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>
}