상세 컨텐츠

본문 제목

React(리액트) 티키타카 30 (SweetAlert2)

React

by e7e 2025. 3. 24. 12:40

본문

그냥 alert를 디버깅이나 프로토타입이 아닌 만약 Production 모드, 곧 

실제 서비스에 사용한다면 그건 거의 예의가 바닥과 키스하는 수준일거시다.

 

많이 사용되는 sweetalert는 react에도 역시 편하게 사용된다. 그냥 한번만 보장

 

설치

npm i sweetalert2  sweetalert2-react-content

 

그냥 보기만 하면 알게 되는 억지스러운 억지 예제 중에서 억지스러울만큼

억지스럽기가 억지스러운 억지스럽기 그지없는 억지 예제

App.jsx

import { useState } from "react";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";

function App() {
  const [userInput, setUserInput] = useState("");

  // https://sweetalert2.github.io/#usage를 참고해서 쓰면 거저 쓰게 됨!
  const getUserInput = () => {
    withReactContent(Swal).fire({
      title: <i>머라 쓸거얌</i>,
      input: "text",
      userInput,
      preConfirm: () => {
        setUserInput(Swal.getInput()?.value || "");
      },
    });
  };

  const justMsg = () => {
    withReactContent(Swal).fire("안농 카리낭 반가벙");
  };

  const successMsg = () => {
    withReactContent(Swal).fire({
      title: "카리낭",
      icon: "success" /* error, info, warning, question */,
      draggable: true,
    });
  };

  const customMsg = () => {
    withReactContent(Swal).fire({
      title: "오 세이니",
      text: "파란 망토와 함께 펄펄",
      imageUrl:
        "https://gdimg.gmarket.co.kr/2283523733/still/280?ver=1637125938",
      imageWidth: 400,
      imageHeight: 200,
      imageAlt: "그저 복사붙여넣기",
      // 아래 preConfirm을 잘 쓰겠네용
      preConfirm: () => {
        setUserInput("세이니닝?");
      },
    });
  };

  const customMsg2 = () => {
    withReactContent(Swal)
      .fire({
        title: "정말이닝?",
        text: "되돌릴수 없다니깡!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "좋아 지워주겠엉",
        cancelButtonText: "암것도 안할꺼얌",
      })
      .then((result) => {
        if (result.isConfirmed) {
          setUserInput("지웠겠징!");
          Swal.fire({
            title: "지웠지롱",
            text: "지웠다냥? 그렇게 쉽겡",
            icon: "success",
          });
        } else {
          setUserInput("");
        }
      });
  };

  return (
    <>
      <h1>띠이작</h1>
      <button onClick={getUserInput}>입력받기</button>
      <button onClick={justMsg}>단순 메세지</button>
      <button onClick={successMsg}>썽꽁 메세지</button>
      <button onClick={customMsg}>커스텀 메세지</button>
      <button onClick={customMsg2}>커스텀 메세지</button>
      <div>입력: {userInput}</div>
    </>
  );
}

export default App;

 

결과는 아래 비스무리

 

소스를 누네 힘주고 보았다면,  withReactContent(Swal).fire 만 받아들인다면 

기존 sweetalert2 사용방식과 거의 완벽하게 똑같다.

 


 

 

 

https://www.youtube.com/watch?v=fSuvy8ALqm0

 

관련글 더보기