Last updated: Apr 7, 2024
Reading timeยท2 min
To open a file input box on button click in React:
onClick
prop on a button element.ref
prop on the file input.inputRef.current.click()
.import {useRef} from 'react'; const App = () => { const inputRef = useRef(null); const handleClick = () => { // ๐๏ธ Open the file input box on click of another 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 the 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;
We used the useRef hook to get access to the file input element.
<input ref={inputRef} style={{display: 'none'}} type="file" onChange={handleFileChange} />
current
property on the ref object to get access to the file input
element on which we set the ref
prop.const handleClick = () => { // ๐๏ธ Open the file input box on click of another element inputRef.current.click(); };
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.
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.
<input ref={inputRef} style={{display: 'none'}} type="file" onChange={handleFileChange} />
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 with 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.
If you need to reset a file input in React, click on the link and follow the instructions.
I've also written a detailed guide on how to show or hide another component on click.
If you need to handle a double-click event in React, check out the following article.