끄적끄적 코딩
Published 2021. 1. 8. 17:38
[React] window.confirm() React
// useConfirm.js

const useConfirm = (message = "", onConfirm, onCancel) => {
  if (!onConfirm || typeof onConfirm !== "function") {
    return;
  }
  if (onCancel && typeof onCancel !== "function") {
    return;
  }
  const confirmAction = () => {
    if (window.confirm(message)) {
      onConfirm();
    } else {
      onCancel();
    }
  };
  return confirmAction;
};

export default useConfirm;
// index.js

import React from "react";
import ReactDOM from "react-dom";
import useConfirm from "./useConfirm";

const App = () => {
  const deleteWorld = () => console.log("Deleting the world...");
  const abort = () => console.log("Aborted");
  const confirmDelete = useConfirm("Are you sure", deleteWorld, abort);
  return (
    <div className="App">
      <button onClick={confirmDelete}>Delete the world</button>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

window.confirm()를 사용하여 확인하는 메시지 창이 나오게 했습니다.
선택 결과에 따라 파라미터로 받은 함수들을 실행시킵니다.

'React' 카테고리의 다른 글

[React] mouseleave  (0) 2021.01.08
[React] beforeunload  (0) 2021.01.08
[React] click 이벤트  (0) 2021.01.08
[React] useRef  (0) 2021.01.08
[React] title  (0) 2021.01.08

검색 태그