EN
React - open file input dialog box on custom button click
0
points
In this article, we would like to show you how to open file input dialog box on button click in React.
To open a file input box on button click, we use a simple trick:
- create invisible file input,
- use
useRef()hook to create reference and assign it to therefproperty of the invisible input, - create a function that simulates the click on the invisible input using the reference,
- assign the function to the onClick property of the button.
Practical example
// ONLINE-RUNNER:browser;
// import React, { useState, useRef } from 'react';
const inputStyle = { display: 'none' }; // assigned to input makes it invisible
const buttonStyle = { /* ... */ };
const pathStyle = { /* ... */ };
const App = () => {
const inputRef = React.useRef(null); // creates reference (to the invisible input)
const [file, setFile] = React.useState(null);
const handleFileChange = (e) => {
const files = e.target.files;
if (files.length > 0) {
const file = files[0];
setFile(file);
} else {
setFile(null);
}
};
const handleButtonClick = () => {
inputRef.current?.click(); // simulates clicking on file input element and opens dialog box
};
return (
<div>
<input ref={inputRef} style={inputStyle} type="file" onChange={handleFileChange} />
<button style={buttonStyle} onClick={handleButtonClick}>Choose file!</button>
{file && <span style={pathStyle}>{file.name}</span>}
</div>
);
};
// export default App;
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);