react get element by id in javascript

In React, you can reference elements in the DOM using refs. Here's an example of how you can get an element by ID in React:

import React, { useRef } from 'react';

function MyComponent() {
  const myElementRef = useRef(null);

  function handleClick() {
    const myElement = myElementRef.current;
    console.log(myElement); // The DOM node with the ID "my-element"
  }

  return (
    <div>
      <div id="my-element" ref={myElementRef}>Hello World</div>
      <button onClick={handleClick}>Get Element by ID</button>
    </div>
  );
}
414 chars
18 lines

In this example, we use the useRef hook to create a reference to the div with the ID "my-element". We then use this reference in the handleClick function to access the DOM node directly.

Note that we're not actually using getElementById here - instead, we're using React's ref system to create a direct reference to the DOM node we're interested in. This can be more efficient than traditional DOM manipulation in some cases, since React uses a virtual DOM to keep track of changes and only updates the parts of the real DOM that actually need updating.

gistlibby LogSnag