File Upload Preview Validate
ReactJS
Hard
6 views
Problem Description
Build an image upload input that previews the image and validates size.
Output Format
Render a React component.
Constraints
Use FileReader for preview and show error when file is too large.
Official Solution
import React, { useState } from 'react';
export default function App() {
const [src, setSrc] = useState('');
const [error, setError] = useState('');
function onFile(e) {
const file = e.target.files && e.target.files[0];
if (!file) return;
if (file.size > 300 * 1024) {
setSrc('');
setError('File too large. Max 300KB');
return;
}
setError('');
const reader = new FileReader();
reader.onload = () => setSrc(String(reader.result || ''));
reader.readAsDataURL(file);
}
return (
<div style={{ padding: 16, width: 560 }}>
<h2 style={{ marginTop: 0 }}>meetcode avatar</h2>
<input type='file' accept='image/*' onChange={onFile} />
{error ? <div style={{ marginTop: 10, color: '#c1121f' }}>{error}</div> : null}
{src ? <img src={src} alt='Preview' style={{ marginTop: 12, width: 160, height: 160, objectFit: 'cover', borderRadius: '50%', border: '1px solid #eee' }} /> : <div style={{ marginTop: 12, color: '#555' }}>No image selected.</div>}
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!