React
[React] 알림 보내기
J3SUNG
2021. 1. 9. 00:57
728x90
// 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() - 알림 권한 요청