How to read and upload a file in React using custom button?

Sometimes, we want to read and upload a file in React using custom button.

In this article, we’ll look at how to read and upload a file in React using custom button.

How to read and upload a file in React using custom button?

To read and upload a file in React using custom button, we can add a hidden file input.

Then we can add a click handler for the button to open the file input.

For instance, we write:

import React, { useRef, useState } from "react";

export default function App() {
  const fileRef = useRef();

  const handleChange = (e) => {
    const [file] = e.target.files;
    console.log(file);
  };

  return (
    <div>
      <button onClick={() => fileRef.current.click()}>
        Custom File Input Button
      </button>
      <input
        ref={fileRef}
        onChange={handleChange}
        multiple={false}
        type="file"
        hidden
      />
    </div>
  );
}

to create a ref with the useRef hook.

Then we add a button and a file input.

We assign fileRef to the file input by setting it as the value of the ref prop.

We add the hidden prop to the input to hide it.

Next, we set the onClick prop of the button to a function that calls fileRef.current.click to open the file selector dialog when we click on it.

Conclusion

To read and upload a file in React using custom button, we can add a hidden file input.

Then we can add a click handler for the button to open the file input.