How to make my button tag to trigger my input tag secretly, without seeing my input tag?

Viewed 38

Question:

I am new to React. For some reason, I would like to hide my input tag. On the other hand, I want a button tag to perform what my existing input do, which is to load file and set the content of files into variables.

Problem explanation:

My input tag could load files and set the file content into variable. However, the style of input tag is not my liking and i prefer the style of my button components. So, as far as I know, only input tag could do the loading file feature.

But since I have wrote the function I need in the input tag, which is to load file and load the content into a variable. I want to see if I can make the button pretended as input. So I dont have to rewrite code again So, is it possible to let my button to somehow pretend the input tag?

Below is my present code:

import React, { useState } from "react";
export function App() {
  const [files, setFiles] = useState("");
  const handleChange = e => {
    const fileReader = new FileReader();
    fileReader.readAsText(e.target.files[0], "UTF-8");
    fileReader.onload = e => {
      console.log("e.target.result", e.target.result);
      setFiles(e.target.result);
    };
  };
  return (
    <>
      <h1>Upload Json file - Example</h1>
      <input type="file" onChange={handleChange} />
      <br />
      {"uploaded file content -- " + files}
      <br />
     // I expect when I click on "Import file", it could also load file like the input tag and perform what my existing input tag do
      <button >Import file</button>
    </>
  );
}
1 Answers

I can see a couple of ways.

One is to give the input element an id and then insert a label inside the button with the for attribute set to the same id.

<input id="upload" type="file" onChange={handleChange}/>

and

<button><label htmlFor="upload">Import file</label></button>

(note: only the clicking on the text will trigger the input, so you might need some css here to make the label fill the button completely)


Another would be to use a ref on the input and use it to trigger a click on it from your button.

const inputRef = useRef<HTMLInputElement>(null);
const handleButtonClick = () => {
  if (inputRef.current) inputRef.current.click();
};

<input ref={inputRef} type="file" onChange={handleChange}/>

<button onClick={handleButtonClick}>Import file</button> 

Both attempts shown at: https://codesandbox.io/s/optimistic-sound-l0hhzm

Related