I am new to using reactJS (and JS in general). I am trying to add a new function to an existing project but it is not compatible because the react dependency is 16.13.1 and does not use hooks apparently. It doesn't accept useState() in the version of the project.
function App() {
const [file, setFile] = useState(); // storing the uploaded file
function handleChange(e) { // function to handle the file upload
console.log(e.target.files);
setFile(URL.createObjectURL(e.target.files[0]));
}
return (
<div className="App">
<h2>Add Image:</h2>
<input type="file" onChange={handleChange} />
<img src={file} />
</div>
);
}
export default App;
I want to make this compatible with that dependency but I have had no luck with my attempts yet. does anyone know how to make it compatible or any resources that can help? sorry if this is an obvious question, I still have a lot to learn! thank you!
What I've tried so far:
class uploadImage extends Component {
constructor(props) {
super(props);
this.state = {
subMenuOpen: false,
file: null
}
this.handleChange = this.handleChange.bind(this)
}
handleChange = (e) => {
this.setState({
file: URL.createObjectURL(e.target.files[0])
})
}
render () {
return (
<div className="App">
<h2>Add Image:</h2>
<input type="file" onChange={handleChange} />
<img src={file} />
</div>
);
}}
maybe you should convert your function into Class Component
try change <img src={file} />
to <img src={this.state.file} />
<input type="file" onChange={handleChange} />
to <input type="file" onChange={this.handleChange} />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.