React 애플리케이션에서 전역적으로 알림 창을 띄우는 기능을 구현하기 위해 useContext 훅과 Material-UI(MUI) 라이브러리를 활용하는 방법을 사용하였다
여기서 Context 란?
context를 이용하면 단계마다 일일이 props를 넘겨주지 않고도 컴포넌트 트리 전체에 데이터를 제공할 수 있게 해준다
- createContext : context 객체를 생성한다.
- Provider : 생성한 context를 하위 컴포넌트에게 전달하는 역할을 한다.
- Consumer : context의 변화를 감시하는 컴포넌트이다.
// 필요한 모듈 import
import React, { createContext, useState, useContext } from "react";
import Snackbar from "@mui/material/Snackbar";
import Alert from "@mui/material/Alert";
import AlertTitle from "@mui/material/AlertTitle";
import VerifiedOutlinedIcon from "@mui/icons-material/VerifiedOutlined";
import Slide from "@mui/material/Slide";
// Alert 컨텍스트 생성
const AlertContext = createContext();
// AlertProvider 컴포넌트 정의
const AlertProvider = ({ children }) => {
const [alerts, setAlerts] = useState([]);
const addAlert = (message) => {
const newAlert = {
message,
open: true,
};
setAlerts((prevAlerts) => [...prevAlerts, newAlert]);
};
const closeAlert = (index) => {
setAlerts((prevAlerts) => {
const updatedAlerts = [...prevAlerts];
updatedAlerts[index].open = false;
return updatedAlerts;
});
};
const AlertComponents = alerts.map((alert, index) => (
<Snackbar
key={index}
anchorOrigin={{ vertical: "top", horizontal: "left" }}
open={alert.open}
onClose={() => closeAlert(index)}
autoHideDuration={3000}
>
<Slide direction="right">
<Alert
severity="warning"
icon={<VerifiedOutlinedIcon />}
sx={{
display: "flex",
flexDirection: "column",
justifyContent: "center",
fontSize: "1.5em",
textAlign: "center",
background: "#fdf3e4",
opacity: "0.2",
color: "#ff9800",
fontSize: "1em",
}}
>
<AlertTitle>알림!</AlertTitle>
{alert.message}
</Alert>
</Slide>
</Snackbar>
));
return (
<AlertContext.Provider value={{ addAlert }}>
{children}
{AlertComponents}
</AlertContext.Provider>
);
};
// 커스텀 훅 useAlert 정의
const useAlert = () => {
const { addAlert } = useContext(AlertContext);
return { addAlert };
};
export { AlertProvider, useAlert };
Alert 컨텍스트 생성하기
createContext()를 사용하여 Alertcontext를 생성한다 =>전역 상태를 공유하기 위해 사용한다
AlertProvider 컴포넌트 정의하기
AlertProvider 컴포넌트를 생성하여 알림 기능을 제공한다
alerts라는 상태 변수를 useState를 사용하여 선언하고 초기값을 빈배열로 설정하여 알림 메세지를 저장하고 관리하는데 사용한다
addAlert 함수를 정의하여 새로운 알림메세지를 추가하고 alerts배열에 새로운 알림 메세지 객체를 추가한다
closeAlert 함수를 정의하여 알림 메세지의 open 속성을 false로 설정하여 화면에 사라지도록 한다
AlertProvider 컴포넌트 사용하기
AlertContext.Provider 컴포넌트를 사용하여 AlertProvider 컴포넌트의 하위 컴포넌트들에게 addAlert 함수를 제공하고
childern을 렌더링하고 AlertComponents를 렌더링하여 알림 메세지를 화면에 표시한다
useAlert 커스텀 훅 정의하기
useContext(AlertContext)를 사용하여 AlertContext에서 addAlert 함수를 가져와 다른 컴포넌트에서 사용할수 있도록한다
import React from "react";
import { useAlert } from "./hook/useAlert";
const App = () => {
const { addAlert } = useAlert();
const handleClick = () => {
addAlert("안녕하세요! 알림입니다.");
};
return (
<div>
<h1>React 알림 예제</h1>
<button onClick={handleClick}>알림 테스트</button>
</div>
);
};
export default App;
'React' 카테고리의 다른 글
Framer-motion 라이브러리(기본) (2) | 2023.12.10 |
---|---|
React-router v6 (2) | 2023.11.26 |
TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'. 에러 (2) | 2023.07.06 |
React-hook-form (0) | 2023.06.18 |
리액트 인풋 에러-Warning: A component is changing an uncontrolled input to be controlled. (0) | 2023.04.26 |