Sometimes, we want to open file browser on the click of a div with React.
In this article, we’ll look at how to open file browser on the click of a div with React.
How to open file browser on the click of a div with React?
To open file browser on the click of a div with React, we can assign a ref to the file input.
And then we can get it and call click
on it when we click on the div.
To do this, we write:
import React, { useRef } from "react";
export default function App() {
const inputFile = useRef(null);
const onClick = (e) => {
inputFile.current.click();
};
return (
<div>
<input
type="file"
id="file"
ref={inputFile}
style={{ display: "none" }}
/>
<button onClick={onClick}>open file browser</button>
</div>
);
}
We create the ref with the useRef
hook.
Then we define the onClick
function that calls inputFile.current.click
to open the file browser.
Next, we assign the the inputFile
ref as the value of the ref
prop of the input so inputFile.current
is set to the file input.
We set the style
prop to { display: "none" }
to hide the file input.
Finally, we add a button and set its onClick
prop to the onClick
function so when we click it, the file browser will show.
Conclusion
To open file browser on the click of a div with React, we can assign a ref to the file input.
And then we can get it and call click
on it when we click on the div.