끄적끄적 코딩
article thumbnail
Published 2021. 1. 9. 00:57
[React] 알림 보내기 React
// useNotification.js

const useNotification = (title, options) => {
  if (!("Notification" in window)) {
    return;
  }
  const fireNotif = () => {
    if (Notification.permission !== "granted") {
      Notification.requestPermission().then((permission) => {
        if (permission === "granted") {
          new Notification(title, options);
        } else {
          return;
        }
      });
    } else {
      new Notification(title, options);
    }
  };
  return fireNotif;
};

export default useNotification;
// index.js

import React, { useEffect, useRef, useState } from "react";
import ReactDOM from "react-dom";
import useNotification from "./useNotification";

const App = () => {
  const triggerNotif = useNotification("Hello, React hooks!", {
    body: "Nice React!",
  });
  return (
    <div className="App">
      <button onClick={triggerNotif}>Notif</button>
    </div>
  );
};

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

브라우저에서 알림을 보내는 코드입니다.

new Notification(title, options);

title 부분에 제목을 입력하고
options 부분에 코드들을 넣을 수 있습니다.

Notification.permission
granted 허용된 상태
denied 허용하지 않은 상태
default 허용에 대한 선택을 하지 않은 상태

Notification.requestPermission() - 알림 권한 요청

'React' 카테고리의 다른 글

[React] Front end 비교 (Svelte, Vue, Angular, React)  (0) 2021.02.02
[React] Axios  (0) 2021.01.09
[React] 전체 화면  (0) 2021.01.09
[React] 스크롤  (0) 2021.01.09
[React] 현재 네트워크 상태 확인  (4) 2021.01.08

검색 태그