Reputation: 63
I'm using this code https://codepen.io/jotavejv/pen/bRdaVJ to add it to my react page.
When I click the Browse button it reloads the page instead of opening the file picker!
I have tried to add:
async function componentDidMount() {
$("#triggerFile").addEventListener("click", evt => {
evt.preventDefault();
$("input[type=file]").click();
}); ...code continues
async does not work.. tried also with
window.onload=function(){}
This too does not work!
When I add the code in a blank page ,it works fine but inside another page it gives me the above error.Smh it should wait for the page to load(or smth similar)
Can someone help me fix this?
thank you
Upvotes: 0
Views: 75
Reputation: 1903
An example of how it can be done in React in this working repl.
import React from 'react';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
this.onBrowseClick = this.onBrowseClick.bind(this);
}
componentDidMount() {
}
onBrowseClick = () => {
this.inputRef.current.click();
};
render() {
return (
<div>
<input type="file" style={{display: 'none'}} ref={this.inputRef}></input>
<button onClick={this.onBrowseClick}>Browse</button>
</div>
);
}
}
export default App;
Upvotes: 1