Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger a click on a different element when clicking an other div

Right now I have a div that is basically a giant square and inside the div I have another div that is simply text that says "Upload File" and a hidden input type = file element as well. When the user presses the div I want to trigger the file upload element. The code I have come up with up until now is:

<div id="test" onClick={this._handleClick}>
   <input type="file" name="image1" accept=".jpg,.jpeg,.png" id="img1" />
   <div id="uploadPhotoButtonText">
       +Add Photo 1
   </div>
</div>

So the file input element I set in CSS as display: none. And once they click anywhere in the div id="test" I want to trigger a click into the file upload element. How can I do all this in react?

I'm thinking it would be something like this but I'm not sure about the syntax and how to go about structuring it:

_handleClick: function() {
  //trigger click into img1
}
like image 547
ogk Avatar asked Jan 02 '16 02:01

ogk


1 Answers

You can use "refs" to refer to nodes inside a component and trigger things on them.


FileBox = React.createClass({
        _handleClick: function(e) {
            var inputField = this.refs.fileField;
            inputField.click()
        },
        render: function() {
            return <div id="test" onClick={this._handleClick}>
                       <input ref="fileField" type="file" name="image1" accept=".jpg,.jpeg,.png" id="img1" />
                       <div id="uploadPhotoButtonText">
                           +Add Photo 1
                       </div>
                   </div>
        }
    })


Read more about refs here: https://facebook.github.io/react/docs/more-about-refs.html

like image 164
Rishav Rastogi Avatar answered Oct 27 '22 23:10

Rishav Rastogi