기록하는 공부

[React/실전형 리액트 Hooks/노마드코더] #2.7 useNotification 본문

Language/Javascript, Typescript, React

[React/실전형 리액트 Hooks/노마드코더] #2.7 useNotification

SS_StudySteadily 2023. 4. 3. 23:42
728x90
반응형

 

강의출처

 

https://youtu.be/WIkZP_8gxm0

 

 

 

 


 

 

useNotification

 

 

useNotification은 React Hooks의 하나로, 

브라우저의 Notification API를 사용하여 웹 페이지에서 알림을 보낼 수 있게 해주는 기능이다.

 

 

이를 사용하면 사용자가 브라우저 창을 닫거나 다른 탭으로 이동해 있을 때도 알림을 보낼 수 있어서,

사용자가 페이지 외부에 있을 때에도 중요한 정보를 전달할 수 있다.

 


useNotification은 useState와 useEffect와 같은 방식으로 사용된다.

컴포넌트 내부에서 호출하여, 브라우저에서 Notification 객체를 생성하고, 알림을 보낼 때 사용되는 함수를 반환한다.

 

 

 

 


 

 

예제코드

 

 

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

const useNotification = (title, options)  => {
  if (!("Notification" in window)) {
    return;
  }
  const fireNotif = () => {
    if (Notification.permission !== "granted") { //permission이 부여되지 않은 경우
      Notification.requestPermission().then((permission) => {
        if (permission === "granted") {
          new Notification(title, options);
        } else return;
      });
    }
  };
  return fireNotif;
  
}

const App = () => {
  const triggerNotif = useNotification(
    "Hello, Can I hack your Computer?",
    {body: "If you agree, I will hack 😈"}
  );
  return (
    <div className="App" style={{ height: "1000vh" }}>
      <button onClick={triggerNotif}>Hello</button>
    </div>
  );
};

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

 

 

이 코드는 React와 Notification API를 사용하여 웹 페이지에서 알림을 보내는 간단한 예제이다.

 


useNotification 함수는 Notification API를 사용하여 알림을 보내는 함수를 반환한다.

이 함수를 실행하면 먼저 브라우저가 Notification API를 지원하는지 확인한다.

Notification API를 지원하지 않는 브라우저인 경우 함수를 종료하고,

지원하는 브라우저인 경우 알림을 보내는 함수를 반환한다.

 


알림을 보내는 fireNotif 함수는 Notification.permission을 사용하여 사용자의 권한을 확인한다.

권한이 부여되지 않은 경우 Notification.requestPermission() 함수를 사용하여 권한을 요청한다.

권한이 부여되면 new Notification(title, options)을 호출하여 알림을 보낸다.

권한이 부여되지 않은 경우 함수를 종료한다.

 


App 컴포넌트에서는 useNotification 함수를 호출하여 triggerNotif 함수를 생성한다. 

버튼을 클릭하면 triggerNotif 함수를 호출하여 알림을 보냅니다.

 

 

 

 


 

 

실행결과

 

 

초기실행화면

 

 

권한 허용 클릭

 

 

윈도우 팝업창이 활성화 됨

 

 

 

 

 


 

 

Notification API에 대해 더 자세히 배우고 싶다면 아래 링크를 통해 확인하도록 하자 !

 

 

https://developer.mozilla.org/en-US/docs/Web/API/Notification/Notification

 

Notification() - Web APIs | MDN

The Notification() constructor creates a new Notification object instance, which represents a user notification.

developer.mozilla.org

 

728x90
반응형