File Input Preview
ReactJS
Hard
6 views
Problem Description
Create a file input that shows a preview of selected image.
Output Format
Render a React component.
Constraints
Use URL.createObjectURL and clean it up when file changes.
Official Solution
import React, { useEffect, useState } from 'react';
export default function App() {
const [file, setFile] = useState(null);
const [url, setUrl] = useState('');
useEffect(() => {
if (!file) {
setUrl('');
return;
}
const nextUrl = URL.createObjectURL(file);
setUrl(nextUrl);
return () => URL.revokeObjectURL(nextUrl);
}, [file]);
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode avatar upload</h2>
<input type='file' accept='image/*' onChange={(e) => setFile((e.target.files && e.target.files[0]) || null)} />
{url ? (
<div style={{ marginTop: 12 }}>
<img src={url} alt='Preview' style={{ width: 180, height: 180, borderRadius: 16, objectFit: 'cover', border: '1px solid #eee' }} />
</div>
) : (
<div style={{ marginTop: 12, color: '#555' }}>Pick an image to preview.</div>
)}
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!