Here's the scenario: a user must upload a file, once he does it, I would want to display it on the page as soon as the server receives it. I tried conditional rendering but that does not work.
What should I do to make it work? Thanks in advance.
code:
import React, { useState } from 'react'
import './App.css'
function App() {
const [image, setImage] = useState('')
const submitHandle = (e) => {
if (!image) {
console.log('please upload an image')
} else {
console.log(e.target)
e.preventDefault()
console.log('submitted')
}
}
return (
<section>
<div>
<div>
<h1>heading one</h1>
<form onSubmit={submitHandle}>
<input
value={image}
onChange={(e) => setImage(e.target.value)}
type='file'
accept='image/gif, image/jpeg, image/png'
/>
<button type='submit'>submit</button>
</form>
{image && <img src={image} alt='image' />}
</div>
</div>
</section>
)
}
export default App
For an input of type file, its value cannot be set by code.
And to view the image immediately, you'll have to convert it into a string using a FileReader;
So we have to create another function loadImage and pass in the selected file as it's argument
function App() {
const [image, setImage] = useState('');
const loadImage = (file) => {
const reader = new FileReader();
reader.addEventListener('load', e => setImage(e.target.result));
reader.readAsDataURL(file);
}
const submitHandle = (e) => {
if (!image) {
console.log('please upload an image')
} else {
console.log(e.target)
e.preventDefault()
console.log('submiited')
}
}
return (
<section>
<div>
<div>
<h1>heading one</h1>
<form onSubmit={submitHandle}>
<input
onChange={(e) => loadImage(e.target.files[0])}
type='file'
accept='image/gif, image/jpeg, image/png'
/>
<button type='submit'>submit</button>
</form>
{image && <img src={image} alt='image' />}
</div>
</div>
</section>
)
}