Ad

Trigger A Click On A Different Element When Clicking An Other Div

- 1 answer

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
}
Ad

Answer

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

Ad
source: stackoverflow.com
Ad