In this article I will show you how to preview your picture in react/JavaScript when you uploaded..........
Create a new project using react (npx create-react-app your-app-name).
create a form component with file input element tag as follows
import { useRef, useState } from 'react';
import './App.css';
import PreviewProfile from './PreviewProfile';
function App() {
const [value, setValue] = useState(null);
const fileRef = useRef(null);
return (
<form>
<input
hidden
type="file"
ref={fileRef}
onChange={(e) => setValue(e.target.files[0])}
/>
{value && <PreviewProfile file={value} />}
<button
type="button"
onClick={() => {
fileRef.current.click();
}}
>
Upload Profile
</button>
</form>
);
}
export default App;
- Let's create another component with PreviewProfile.jsx (as your desire) and write the following code:
import React, { useState } from 'react';
function PreviewProfile({ file }) {
const [preview, setPreview] = useState(null);
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
setPreview(reader.result);
};
return (
<div>
<img
src={preview}
alt="preview"
style={{ width: '50px', height: '50px', borderRadius: '50%' }}
/>
</div>
);
}
export default PreviewProfile;
and run your application and upload an image and that's all.
Top comments (0)