JS

import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
const ImageUploadStyled = styled.div`
margin-bottom: 2rem;
`;
const Upload = ({ setBase64, receivedFile }) => {
const [fileInputState, setFileInputState] = useState('');
const [previewSource, setPreviewSource] = useState(receivedFile || undefined);
const [successMsg, setSuccessMsg] = useState('');
const previewFile = (file) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
setPreviewSource(reader.result);
};
};
const handleFileInputChange = (e) => {
const file = e.target.files[0];
previewFile(file);
setFileInputState(e.target.value);
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
setBase64(JSON.stringify(reader.result));
setSuccessMsg('Upload finished!');
};
};
const handleSubmitFile = (e) => {
e.preventDefault();
};
useEffect(() => {
setPreviewSource(receivedFile);
}, [receivedFile]);
return (
<ImageUploadStyled>
<h1 className="title">Upload an Image</h1>
{successMsg && <p className="color__green bold">{successMsg}</p>}
<div onSubmit={(e) => handleSubmitFile(e)} className="form">
<input
id="fileInput"
type="file"
name="image"
onChange={handleFileInputChange}
value={fileInputState}
className="form-input"
/>
</div>
{previewSource && (
<p className="bold">Choose a new file if you want to change image</p>
)}
{previewSource && (
<img src={previewSource} alt="chosen" style={{ height: '300px' }} />
)}
</ImageUploadStyled>
);
};
export default Upload;