Open a file input box on button click in React

avatar

Borislav Hadzhiev

Last updated: Apr 24, 2022

banner

Check out my new book

Open a file input box on button click in React #

To open a file input box on button click in React:

  1. Set the onClick prop on a button element.
  2. Set the ref prop on the file input.
  3. When the button gets clicked, open the file input box, e.g. inputRef.current.click().
App.js
import {useRef} from 'react'; const App = () => { const inputRef = useRef(null); const handleClick = () => { // 👇️ open file input box on click of other element inputRef.current.click(); }; const handleFileChange = event => { const fileObj = event.target.files && event.target.files[0]; if (!fileObj) { return; } console.log('fileObj is', fileObj); // 👇️ reset file input event.target.value = null; // 👇️ is now empty console.log(event.target.files); // 👇️ can still access file object here console.log(fileObj); console.log(fileObj.name); }; return ( <div> <input style={{display: 'none'}} ref={inputRef} type="file" onChange={handleFileChange} /> <button onClick={handleClick}>Open file upload box</button> </div> ); }; export default App;

open file input on button click

We used the useRef hook to get access to the file input element.

Notice that we have to access the current property on the ref object to get access to the file input element on which we set the ref prop.

When we pass a ref prop to an element, e.g. <input type="file" ref={myRef} />, React sets the .current property of the ref object to the corresponding DOM node.

We can call the click() method, e.g. ref.current.click() to simulate a mouse click on the file input element.

When the click() method is used on an element, it triggers the element's click event. When the click event on a file input is triggered, the file upload dialog opens.

Notice that we set the display property of the file input to none to hide it.

Now when the user clicks on the button element, we simulate a click on the file input using the ref object and the file upload box opens.

This approach works any any type of element, e.g. a div or an icon. Simply set the onClick prop on the element and simulate a click on the file input when the element gets clicked.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.