DEV Community

Cover image for Display a phone (or any other PNG file) with a customizable background image and an optional dark theme
Lucas Su
Lucas Su

Posted on

Display a phone (or any other PNG file) with a customizable background image and an optional dark theme

Import Statements

import { cn } from '@/lib/utils';
import { HTMLAttributes } from 'react';
Enter fullscreen mode Exit fullscreen mode
  • import { cn } from '@/lib/utils': This imports a utility function named cn from a file located at @/lib/utils. The cn function is typically used to concatenate class names conditionally.

  • import { HTMLAttributes } from 'react': This imports the HTMLAttributes type from React. It is used to extend the properties of the PhoneProps interface.

Interface Definition

interface PhoneProps extends HTMLAttributes<HTMLDivElement> {
  imgSrc: string;
  dark?: boolean; 
}
Enter fullscreen mode Exit fullscreen mode

The interface means PhoneProps will include all the standard properties of a div element, plus any additional properties defined within it. An optional property dark of type boolean which determines the theme of the phone template (dark or white edges).

Component Definition

const Phone = ({ imgSrc, className, dark = false, ...props }: PhoneProps) => {
Enter fullscreen mode Exit fullscreen mode

This defines a functional component named Phone that takes props matching the PhoneProps interface. It destructures imgSrc, className, dark (defaulting to false if not provided), and any other props.

JSX Return

return (
  <div
// concatenate the default class names with any additional 
// class names passed as className prop.
    className={cn(
      'relative pointer-events-none z-50 overflow-hidden',
      className
    )}
    {...props}>
    <img
      src={
        dark
          ? '/phone-template-dark-edges.png'
          : '/phone-template-white-edges.png'
      }
      className='pointer-events-none z-50 select-none'
      alt='phone image'
    />

    <div className='absolute -z-10 inset-0'> // set z index to -10
      <img
        className='object-cover min-w-full min-h-full'
        src={imgSrc}
        alt='overlaying phone image'
      />
    </div>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Summary

The Phone component renders a div containing two images:

  1. An image of a phone template, which changes based on the dark prop.
  2. An overlay image (imgSrc) positioned absolutely behind the phone template image.

This setup allows you to display a phone with a customizable background image and an optional dark theme.

Outcome

Image description

Important

These are my study notes for the casecobra project by josh tried coding on youtube.

Top comments (0)