Language/React.js

리액트 Tailwind(css) Alert(알림) Component(컴포넌트)

  • -
반응형

1. 리액트 tailwindcss 알림(Alert) 컴포넌트란?

리액트와 tailwindcss는 현대적인 웹 개발에서 인기 있는 프레임워크 및 라이브러리입니다. 리액트는 사용자 인터페이스를 구축하기 위한 JavaScript 라이브러리이고, tailwindcss는 스타일링을 위한 CSS 프레임워크입니다. 이 둘을 결합하여 리액트 tailwindcss 알림 컴포넌트를 만들 수 있습니다.

알림 컴포넌트는 사용자에게 중요한 정보를 전달하거나 상호 작용을 유도하는 데 사용됩니다. 예를 들어, 경고, 성공 메시지, 알림 메시지 등을 표시할 수 있습니다. 이러한 알림은 웹 애플리케이션의 사용자 경험을 향상시키고 사용자에게 필요한 정보를 제공하는 데 도움이 됩니다.

 

2. 왜 리액트와 tailwindcss를 함께 사용하는가?

리액트와 tailwindcss를 함께 사용하는 것은 개발자에게 다양한 이점을 제공합니다.

첫째로, 리액트는 가상 DOM (Virtual DOM)을 사용하여 성능을 향상시킵니다. 가상 DOM은 변경된 부분만 실제 DOM에 적용하므로 전체 페이지를 다시 렌더링할 필요가 없어집니다. 이는 알림 컴포넌트와 같은 동적인 요소를 효율적으로 처리하는 데 도움이 됩니다.

둘째로, tailwindcss는 사전 정의된 스타일 유틸리티 클래스를 제공하여 스타일링을 더 쉽게 만듭니다. 클래스를 조합하여 원하는 스타일을 쉽게 적용할 수 있으며, 반응형 디자인을 쉽게 구현할 수 있습니다. 이는 알림 컴포넌트의 모양과 레이아웃을 유연하게 구성하는 데 도움이 됩니다.

 

3. 컴포넌트 예시 (코드)

react alert component

Alert Component(알림 컴포넌트)

import React, { useState, useEffect } from 'react';

interface IAlertProps {
    icon: JSX.Element;
    headline: string;
    headlineColor: 'text-green-600' | 'bg-red-600';
    content: JSX.Element;
    hideClose?: boolean;
    bgColor: 'bg-green-100' | 'bg-red-100';
    timer?: number;
}

const Alert = ({ icon, headline, headlineColor, hideClose, timer, bgColor, content }: IAlertProps) => {
    const [isAlertOpen, setAlert] = useState(true);

    useEffect(() => {
        if (timer) {
            const timeId = setTimeout(() => {
                // After xx seconds set the show value to false, if exist timer as props
                setAlert(false);
            }, timer);

            return () => {
                clearTimeout(timeId);
            };
        }
    }, [timer]);

    const closeAlert = () => {
        setAlert(false);
    };

    return (
        <>
            {isAlertOpen && (
                <div className="fixed max-w-fit top-0 right-0 left-0 mx-auto mt-4 z-50">
                    <div className={`relative flex w-full rounded-lg p-4 ${bgColor}`}>
                        {!hideClose && (
                            <div
                                role="button"
                                className="absolute rounded-lg p-1 right-0 top-0 mr-2 mt-2"
                                onClick={closeAlert}
                            >
                                <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    className="h-6 w-6"
                                    viewBox="0 0 24 24"
                                    stroke="currentColor"
                                    stroke-width="2"
                                >
                                    <path
                                        stroke-linecap="round"
                                        stroke-linejoin="round"
                                        d="M6 18L18 6M6 6l12 12"
                                    ></path>
                                </svg>
                            </div>
                        )}

                        <div className={`flex w-8 h-8 ${headlineColor}`}>{icon}</div>
                        <div className="px-2">
                            <span className={`mb-2 font-bold ${headlineColor}`}>{headline}</span>
                            <div>{content}</div>
                        </div>
                    </div>
                </div>
            )}
        </>
    );
};

export default Alert;

Props 설명

icon :  말그대로 svg 형식의 아이콘이다. 예시화면에서는 체크 표시의 아이콘을 의미한다

headline & headlineColor : 제목을 string형식으로 넣고, 색상은 tailwindcss `text...` 로 꾸민다. (필수, 수정 가능)

content : content는 jsx 면 어떤 형식으로 들어가도 되며, 필수로 넣어야한다.

hideClose : 우측 닫기 버튼으로 비활성화 시킬 수도 있다.

bgColor : Alert 창의 바탕색상으로 역시 tailwincss `bg...`를 이용해서 넣으면 된다.

timer : setTimeout & clearTimeout으로 창이 얼마 뒤에 사라지게 하는가를 의미한다. 예시에서는 3초(3000)가 입력되었다.

 

Alert Component 사용하기(import) 예시

            <Alert
                timer={3000}
                headline="Success"
                headlineColor="text-green-600"
                bgColor="bg-green-100"
                content={<span className="text-sm">Login succesful</span>}
                icon={
                    <svg
                        clip-rule="evenodd"
                        fill-rule="evenodd"
                        stroke-linejoin="round"
                        stroke-miterlimit="2"
                        viewBox="0 0 24 24"
                        xmlns="http://www.w3.org/2000/svg"
                        fill="currentColor"
                        stroke="currentColor"
                    >
                        <path
                            d="m11.998 2.005c5.517 0 9.997 4.48 9.997 9.997 0 5.518-4.48 9.998-9.997 9.998-5.518 0-9.998-4.48-9.998-9.998 0-5.517 4.48-9.997 9.998-9.997zm0 1.5c-4.69 0-8.498 3.807-8.498 8.497s3.808 8.498 8.498 8.498 8.497-3.808 8.497-8.498-3.807-8.497-8.497-8.497zm-5.049 8.886 3.851 3.43c.142.128.321.19.499.19.202 0 .405-.081.552-.242l5.953-6.509c.131-.143.196-.323.196-.502 0-.41-.331-.747-.748-.747-.204 0-.405.082-.554.243l-5.453 5.962-3.298-2.938c-.144-.127-.321-.19-.499-.19-.415 0-.748.335-.748.746 0 .205.084.409.249.557z"
                            fill-rule="nonzero"
                        />
                    </svg>
                }
            />

Codesandbox

 

참조

https://tailwindcomponents.com/component/alert-messages

 

Alert messages | Widget

'Alert messages with icons'

tailwindcomponents.com

 

 
반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.