Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react open file browser on click a div

Tags:

reactjs

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 ??

like image 575
varad Avatar asked May 26 '16 09:05

varad


People also ask

How do I open a browser file 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.

Can onClick be used with DIV in React?

To set your mind at ease, the onClick event does work with divs in react, so double-check your code syntax.


1 Answers

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

like image 143
Angel Avatar answered Sep 18 '22 15:09

Angel