Borislav Hadzhiev
Last updated: Apr 24, 2022
Check out my new book
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 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;
We used the useRef hook to get access to the file input element.
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.
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.