React.js > Network 접속 상태 출력하기
- Web API: navigator.online
- React Hooks: useEffect, useState
- Event: online, offline, onchange
- Network가 온라인 상태일 때, 화면과 콘솔에 On/Off-line 상태 출력
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
const useNetwork = onChange => {
const [status, setStatus] = useState(navigator.onLine);
const handleChange = () => {
if(typeof onChange === "function"){
onChange(navigator.onLine);
}
setStatus(navigator.onLine);
}
useEffect(() => {
window.addEventListener("online", handleChange);
window.addEventListener("offline", handleChange);
return() => {
window.removeEventListener("online", handleChange);
window.removeEventListener("offline", handleChange);
};
}, []);
return status;
}
const App = () => {
const handleNetworkChange = (online) => {
console.log(online ? "Status: Online" : "Status: Offline")
}
const onLine = useNetwork(handleNetworkChange);
return (
<div>
<h1>{onLine ? "Online" : "Offline"}</h1>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);