Search code examples
javascriptreactjstypescriptdebuggingrefactoring

Can I remove document.getElementById in reactjs?


Can I change the prop value without

document.getElementById(objRef.uid + "_size" ).value = val

note that these dropdowns are being made in a for loop, and there are thousands of them.

<DropDownMenu 
    id={objRef.uid + "_size"} 
    setValue={( val ) => { document.getElementById( objRef.uid + "_size" ).value = val }} 
    value={objRef.size} 
    colors={["bg-red-500", "bg-yellow-400", "bg-emerald-400"]} 
    options={["Small", "Medium", "Large"]} />

Solution

  • yes you can. you can use the useRef hook.

    example of using it (you can remember that each HTML element get a ref properties that you an implement a value in it, in example you see an input element but it is the same for div and more)

     function App() {
      const inputElement = useRef();
    
      const focusInput = () => {
        inputElement.current.focus();
      };
    
      return (
        <>
          <input type="text" ref={inputElement} />
          <button onClick={focusInput}>Focus Input</button>
        </>
      );
    }