DEV Community

Rezzak
Rezzak

Posted on

How to preview your uploaded profile picture in front-end when you uploaded

In this article I will show you how to preview your picture in react/JavaScript when you uploaded..........

  1. Create a new project using react (npx create-react-app your-app-name).

  2. 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;
Enter fullscreen mode Exit fullscreen mode
  1. 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;
Enter fullscreen mode Exit fullscreen mode

and run your application and upload an image and that's all.

Top comments (0)