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 theref
property 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.
xxxxxxxxxx
1
// import React, { useState, useRef } from 'react';
2
3
const inputStyle = { display: 'none' }; // assigned to input makes it invisible
4
const buttonStyle = { /* ... */ };
5
const pathStyle = { /* ... */ };
6
7
const App = () => {
8
const inputRef = React.useRef(null); // creates reference (to the invisible input)
9
const [file, setFile] = React.useState(null);
10
11
const handleFileChange = (e) => {
12
const files = e.target.files;
13
if (files.length > 0) {
14
const file = files[0];
15
setFile(file);
16
} else {
17
setFile(null);
18
}
19
};
20
21
const handleButtonClick = () => {
22
inputRef.current?.click(); // simulates clicking on file input element and opens dialog box
23
};
24
25
return (
26
<div>
27
<input ref={inputRef} style={inputStyle} type="file" onChange={handleFileChange} />
28
<button style={buttonStyle} onClick={handleButtonClick}>Choose file!</button>
29
{file && <span style={pathStyle}>{file.name}</span>}
30
</div>
31
);
32
};
33
34
// export default App;
35
36
const root = document.querySelector('#root');
37
ReactDOM.render(<App />, root);