Open an input file on a button click in React

The default input file upload button design is unattractive. You may need to upload a file when an external div or button is clicked, therefore today we’ll teach you how to open an input file in React when a button is clicked.

Demo Application

Output - Open an input file on a button click in React - Clue Mediator
Output – Open an input file on a button click in React – Clue Mediator

Steps to Open an input file on a button click in React

  1. Add button and file input in component
  2. Handle input file event through refs
  3. Output

1. Add button and file input in component

First, we have to add the button and input file in the React component. Make sure input file is hidden via CSS.

App.js
index.css

2. Handle input file event through refs

Now let’s trigger the input file onChange event on a button click using refs. Here, we will use the useRef Hook to trigger the function.

First, create a input ref hook.

Then set it to the input file.

Now, trigger the click event using ref via the button click event.

3. Output

Put all the code together and see how it looks.

App.js

Run the application and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *