react open file browser on click a div
import React from 'react';
const Content = () => {
const handleClick = (e) => {
const fileInput = document.getElementById('file');
fileInput.click();
};
const handleFileSelect = (e) => {
const selectedFile = e.target.files[0];
console.log(selectedFile);
};
return (
<div className="body-content">
<div className="add-media" onClick={handleClick}>
<i className="plus icon"></i>
<input type="file" id="file" style={{ display: 'none' }} onChange={handleFileSelect} />
</div>
</div>
);
};
export default Content;
In this example, we use two separate functions to handle the click event on the add-media
div and the selection of a file using the file input.
The handleClick
function is called when the user clicks the add-media
div with the icon. This function retrieves the file input element using the getElementById
method and simulates a click on it using the click
method.
The handleFileSelect
function is called when the user selects a file using the file input. This function retrieves the selected file from the target.files
array and logs it to the console.
Both of these functions are passed as callbacks to the relevant events using the onClick
and onChange
props.
Comments
Post a Comment