React-Toastify 커스텀하기 (with Styled-Components)

성홍제·2025년 3월 25일
post-thumbnail

React-Toastify 기능중에서는 커스텀을 할 수 있는 기능이 있다.
오늘 한 번 자신의 입맛대로 커스텀을 해보자.

Props, Option 지정

import { Flip, toast, ToastOptions } from 'react-toastify'
import { Success, Error, Info } from '~/assets'

interface ToastProps {
    type: 'success' | 'error' | 'info'
    message: string
}

const toastOptions: ToastOptions = {
    position: 'top-right',
    autoClose: 2000,
    pauseOnHover: false,
    pauseOnFocusLoss: false,
    closeOnClick: false,
    closeButton: false,
    transition: Flip,
}
  • 재사용 가능하도록 props로 받아온다.
  • Option은 라이브러리에서 기본적으로 제공한다. (공식문서를 보는것을 추천)

토스트 만들기

export const Toastify = ({message, type}: ToastProps) => {
    switch (type) {
      case 'success':
        toast.success(message, {
            ...toastOptions,
            icon: <img src={Success} alt='success' width={25} height={25}/>,
          })
          return;
      case 'error':
        toast.error(message, {
            ...toastOptions,
            icon: <img src={Error} alt='error' width={22} height={22}/>,
          })
          return
      case 'info':
        toast.info(message, {
            ...toastOptions,
            icon: <img src={Info} alt='info' width={25} height={25}/>,
          })
          return
      default:
        toast(message, toastOptions)
    }
  }

스타일

import styled from 'styled-components'
import { ToastContainer as ReactToastContainer } from 'react-toastify'

export const ToastCont = styled(ReactToastContainer)`
  .Toastify__toast {
    width: 21rem;
    background-color: #fff;
    color: #000;
    border-radius: 8px;
    padding: 10px;
    font-size: 15spx;
    font-weight: 400;
    display: flex;
    align-items: center;
  }

  .Toastify__progress-bar {
    height: 5px;
    border-radius: 2px;
  }

   .Toastify__toast--success .Toastify__progress-bar {
    background-color: rgb(76, 175, 80) !important;
  }

  .Toastify__toast--error .Toastify__progress-bar {
    background-color: rgb(220, 53, 69) !important;
  }

  .Toastify__toast--info .Toastify__progress-bar {
    background-color: rgb(0, 134, 107) !important; 
  }
`
  • 직접 스타일 수정도 가능하니 공식문서 보는것을 추천한다.
profile
열심히 살고 있어요

0개의 댓글