4

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

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

1 Comment

Why the down vote? at the very least this is a duplicate of the question I linked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.