Languages
[Edit]
EN

React - open file input dialog box on custom button click

0 points
Created by:
Wesley
501

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:

  1. create invisible file input,
  2. use useRef() hook to create reference and assign it to the ref property of the invisible input,
  3. create a function that simulates the click on the invisible input using the reference,
  4. 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);

 

Alternative titles

  1. React - open file input dialog box on another element click
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join