develop
PublishDate13 Feb 2023
Implementing Profile Picture Preview and File Uploader with React.js

The profile picture preview and file uploader that needs to be implemented executes a file upload when the Profile Picture Preview is clicked. The design features a default image for the profile picture preview with text inside it. The development environment includes TypeScript, React, Next.js, and emotion/styled.


UploadProfileImage

This is an SVG created to be similar to the original due to copyright reasons.


Let’s try implementing it

File Uploader

import styled from '@emotion/styled';
import { uploadImage } from '@root/utils/assets';
const Upload = () => {
return (
<StyledImageLabel
style={{
backgroundImage: `url(${uploadImage})`,
backgroundSize: '100%',
}}
></StyledImageLabel>
);
};
export default Upload;
const StyledImageLabel = styled.label`
width: 166px;
height: 166px;
`;
import { uploadImage } from '@root/utils/assets';
<StyledImageUploader type="file" accept="image/*" id="profileImage" />
<StyledImageUploader type="file" accept="image/*" id="profileImage" />

Uploader

We set the default image for the file uploader.

Uploader

We input the editable text and set the position according to the design.

Uploader

Set the htmlFor attribute of the label tag and the id attribute of the input tag to be the same. Now, clicking the image will open the image file selection window.

Preview Profile Image

import React, { useRef, useState } from 'react';
const Upload = () => {
const [image, setImage] = useState<string>('');
const imgRef = useRef<HTMLInputElement>(null);
return (
<StyledImageLabel
htmlFor="profileImage"
style={{
backgroundImage: `url(${image || uploadImage})`,
backgroundImage: `url(${uploadImage})`,
}}
>
<StyledImageText>편집</StyledImageText>
<StyledImageUploader type="file" accept="image/*" id="profileImage" />
</StyledImageLabel>
);
};
export default Upload;
`;
const updateImage = (e: React.ChangeEvent<HTMLInputElement>) => {
backgroundImage: `url(${image || uploadImage})`,
const StyledImageLabel = styled.label`
const updateImage = (e: React.ChangeEvent<HTMLInputElement>) => {
const StyledImageLabel = styled.label`

To implement the profile picture preview, import useRef and useState.

Set up the ref and styles so that when the profile picture changes, the preview image updates accordingly.

Uploader

We can complete the profile picture preview implementation by writing the updateImage arrow function and assigning it to the onChange event.

Uploader

When using a non-square image, it may appear repeated, as shown in the above image. We can control the repeating method of the background image using the background-repeat property[1].

Uploader

The background-repeat[1] has several options, and if we set it to no-repeat, we can achieve a result like the image above.

Reference

© 2024

Park Gadan

33°06'56.2"-38°34'03.5"