Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger onChange on <input type='file' /> by another Button click in ReactJS?

<div style={{display: 'grid'}}>
    <button id='plus' onClick={???}>+</button>
    <input id='selectImage' type="file" onChange={fileSelectHandler} />
</div>

Here, I want to trigger the onChange function of input, by clicking the button. How to solve this issue?

like image 962
techKid-Rinshad Avatar asked Aug 26 '18 10:08

techKid-Rinshad


People also ask

How do you write onChange in React?

import React from "react"; function App() { return ( <input type="text" name="firstName" onChange={event => console. log("onchange is triggered")} /> ); } export default App; Now whenever you type something into the text box, React will trigger the function that we passed into the onChange prop.


1 Answers

Create a ref:

//inside the constructor:
fileRef = React.createRef()
// in your input element
<input id='selectImage' type="file" onChange={fileSelectHandler} ref={this.fileRef} />

Now,

<button id='plus' onClick={this.triggerClick}>+</button>

triggerClick() {
  this.fileRef.current.click()
}
like image 51
Bhojendra Rauniyar Avatar answered Sep 28 '22 10:09

Bhojendra Rauniyar