My react component:
import React, { PropTypes, Component } from 'react' class Content extends Component { handleClick(e) { console.log("Hellooww world") } render() { return ( <div className="body-content"> <div className="add-media" onClick={this.handleClick.bind(this)}> <i className="plus icon"></i> <input type="file" id="file" style={{display: "none"}}/> </div> </div> ) } } export default Content
Here when I click a div with icon I want to open a <input>
file which shows me option to select photos. After selecting the photos I want to get the value which photo is selected. How can I do this in react ??
To open a file input box on button click in React: Set the onClick prop on a button element. Set the ref prop on the file input. When the button gets clicked, open the file input box, e.g. inputRef.
To set your mind at ease, the onClick event does work with divs in react, so double-check your code syntax.
Upload a new answer using React Hooks
First create your Input ref hook
const inputFile = useRef(null)
Then set it to your INPUT and add a style to display:none for the input will not show in the screen
<input type='file' id='file' ref={inputFile} style={{display: 'none'}}/>
Then create your function to handle the open file, the function should be inside the same function you are using the useRef Hook
const onButtonClick = () => { // `current` points to the mounted file input element inputFile.current.click(); };
Then set the funcion to a Button element
<button onClick={onButtonClick}>Open file upload window</button>
API for HTML INPUT FILE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With