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.
Checkout more articles on ReactJS
Demo Application
Steps to Open an input file on a button click in React
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import React, { useState } from 'react'; function App() { const [file, setFile] = useState([]); const handleChange = e => { setFile([...file, e.target.files[0]]); } return ( <div className="app"> <h3>Open an input file on a button click in React - <a href="https://www.cluemediator.com" target="_blank" rel="noreferrer noopener">Clue Mediator</a></h3> <button onClick={() => { }}> <img src="https://www.svgrepo.com/show/12604/paper-clip.svg" /> </button> <input type="file" onChange={handleChange} /> <strong>Uploaded Files:</strong> {file.map(x => x.name).join(', ')} </div> ); } export default App; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | button { cursor: pointer; background: transparent; border: 0; } button:focus { outline: none; } button img { width: 20px; height: 20px; } input[type=file] { display: none; } |
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.
1 | const inputFile = useRef(null); |
Then set it to the input file.
1 2 3 4 | <input type="file" onChange={handleChange} ref={inputFile} /> |
Now, trigger the click event using ref
via the button click event.
1 2 3 4 | <button onClick={() => inputFile.current.click()}> <img src="https://www.svgrepo.com/show/12604/paper-clip.svg" /> </button> |
3. Output
Put all the code together and see how it looks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import React, { useState, useRef } from 'react'; function App() { const [file, setFile] = useState([]); const inputFile = useRef(null); const handleChange = e => { setFile([...file, e.target.files[0]]); } return ( <div className="app"> <h3>Open an input file on a button click in React - <a href="https://www.cluemediator.com" target="_blank" rel="noreferrer noopener">Clue Mediator</a></h3> <button onClick={() => inputFile.current.click()}> <img src="https://www.svgrepo.com/show/12604/paper-clip.svg" /> </button> <input type="file" onChange={handleChange} ref={inputFile} /> <strong>Uploaded Files:</strong> {file.map(x => x.name).join(', ')} </div> ); } export default App; |
Run the application and check the output in the browser.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂