- Instant help with your JavaScript coding problems

Get element by ID in React

Question:
How to get element by ID in React?
Answer:
const myRef = useRef();

useEffect(()=>{
    myRef.current = document.getElementById('my-element');
},[]);
Description:

If you build a new React component into an old legacy code, you cannot always use the ref attribute provided by React for that HTML element. In such a case, you can use the basic JavaScript document.getElementById method to find the element. You can store the founded element in a useRef variable. What is important is that you only search for the element once the entire page has loaded. You can achieve this by searching for the element in a useEffect hook.

const myRef = useRef();

useEffect(()=>{
    myRef.current = document.getElementById('my-element');
},[]);
Share "How to get element by ID in React?"
Related snippets:
Tags:
get, access, element, by id, react
Technical term:
Get element by ID in React