How to set useRef for html element manually after mounting

Viewed 34

For context, I have a react app with a tree explorer. When the user hovers a node, I show a menu for 5 seconds using a setTimeout inside a useEffect. I want to be able to set a ref on a file input element in the menu but the ref is always null. How can I update the ref after it has been mounted? The issue it seems is that the input is not mounted until the tree node is hovered but the component the input node is created in has already been mounted.

------------- EDIT -----------

The following code snippet works. The key seems to be the e.stopPropagation(). I thought a ref would have been a better choice but it did not seem to work.


// component
 
  const [showControls, setShowControls] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => {
      setShowControls(false);
    }, 5000);
    return () => clearTimeout(timer);
  }, [showControls]);

  const handleChange = (e) => {
    console.log('handleChange...');
  }

  const onButtonClick = (e) => {
    e.stopPropagation();
    e.preventDefault();
    const el = document.querySelector("input[type=file]");
    el.click();
  };


  // some other code...

  return (
    //...other jsx

    { showControls && (
      <>
        <IconButton onClick={onButtonClick} />
        <input
          id="hiddenFileInput"
          type="file"
          onClick={(e) => e.stopPropagation()}
          onChange={handleChange}
          style={{display: 'none'}}
        />
      </>
    )}
  );



0 Answers
Related