Reputation: 800
I've got a file selector, when clicking the button, the file selector shows up:
<input id='example' type="file" accept="image/*" onChange={this.onImageChange} />
Now I want to use another button to do that, trigger the input above :
<button onClick={() => {
var element = document.getElementById('example');
console.log(element) // This shows <input id="example" type="file" accept="image/*">
// element.onChange() // Error: onChange() is not a function
// Above doesn't work, so I try to trigger the onChange event manually,
// but below doesn't do anything
var event = new Event('change');
element.dispatchEvent(event);
}}></button>
Upvotes: 4
Views: 15141
Reputation: 1201
element.onChange
is not a method because your onChange function is stored in your react Component class and delegated via React's synthetic event emitter. It is a property of React.createElement('input')
, but is not a property of an actual DOM element.
To call your React element's onChange method, you can call it directly, like
this.onChange(event)
.
The problem with that methodology is your event will not have a target attached to it.
The change method is meant to provide an interface for controlling the value of inputs, so if you want to change the file attached to the input, you should simply change its value in state.
this.setState({file: this.alternateFile})
Upvotes: 1
Reputation: 871
If that is react you should not access the Dom for those kind of stuff. They have one Api to give you what you need.
You want one uncontroller component. In order to do that you can use one reference.
I havent tried but i think you can do this.
Create the ref on the constructor
this.inputRef = React.createRef();
Then assign the input ref prop to this.inputRef
<input ref={this.inputRef} id='example' type="file" accept="image/*" onChange={this.onImageChange} />
And lately dispatch the click.
this.inputRef.current.click();
Hope it works
Upvotes: 4
Reputation: 6220
The onChange function is a callback AFTER a file has been selected.
If what you want is to show the file selector with another button, you can take a look into this answer
Bear in mind, because of security reasons you need to trigger the selector on the onClick function, user input IS NECESSARY.
Upvotes: 0