Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use useRef for the attribute htmlFor?

I want to customize the input tag for file upload. This is my code. Here for the attribute htmlFor, I am giving id of the input tag.Then it is working. But instead I want to use useRef ref. How can I do that ? If I follow the below method, it will be problematic if I render this component more than once. right ?

const App = () => {
  const inputRef = useRef(null);
  const [file, setFile] = useState(null);
  return (
    <>
      <input
        ref={inputRef}
        accept=".pdf"
        style={{ display: "none" }}
        id="raised-button-file"
        multiple
        type="file"
        onChange={e => {
          setFile(e.target.files[0]);
        }}
      />
      <label htmlFor="raised-button-file">
        <button component="span">
          <span>file</span>
        </button>
      </label>
    </>
  );
};
like image 734
Abidh Avatar asked Nov 23 '19 07:11

Abidh


1 Answers

Another way of using <label> tag is by wrapping your element as a child without specifying an id for it.

<label>
  <input
    accept=".pdf"
    style={{ display: "none" }}
    multiple
    type="file"
    onChange={e => {
      setFile(e.target.files[0]);
    }}
  />
  <span>File</span>
</label>

If you prefer to open your file input dialog with your ref, you can do like this.

const handleOpenFileInput = () => {
  inputRef.current.click();
};
<label onClick={handleOpenFileInput}>
  <button>file</button>
</label>
<input
  ref={inputRef}
  accept=".pdf"
  style={{ display: "none" }}
  multiple
  type="file"
  onChange={e => {
    setFile(e.target.files[0]);
  }}
/>
like image 90
junwen-k Avatar answered Sep 29 '22 20:09

junwen-k