tại file pages/_app.tsx bạn nên bao tất cả bởi một
<MainLayoutProvider>{your some thing}</MainLayoutProvider>
Như bạn biết, NextJS hay ReactJS là framework một chiều chỉ truyền từ component cha sang component con. Vì vậy, bạn không thể giao tiếp với các component không liên quan.
- Ví dụ: khi bạn xảy ra một event nào đó mà bạn muốn nó tác động đến Header của bạn hay ngược lại. Như bạn biết đó, Header và Footer thông thường được setup độc lập vì vậy chúng không có liên kết với bất kỳ component nào. Vậy làm thế nào để chúng ta nhận sự thay đổi từ chúng.
- Giải pháp của tôi chính là MainLayoutProvider. MainLayoutProvider ở đây sẽ đóng vai trò là một thành phần cha có chức năng tương tự như redux hay store. Nó có thể nhận và export ra các state mà bạn muốn ở bất cứ đâu trên trang web.
- Hãy tưởng tượng rằng MainLayoutProvider là một nơi trung gian thứ ba khi bạn muốn giao tiếp giữa hai component không liên quan như ví dụ bên trên. Thay vì bạn giao tiếp trực tiếp thì bạn có thể đẩy event, data, ... vào trung gian này và phía bên kia sẽ lấy chúng ra từ trung gian đó.
- Dưới đây là ví dụ khởi tạo một Providerimport React, { useContext } from "react";
import { useState } from "react";
interface MainLayoutContextValue {
isShowCart: boolean;
setIsShowCart: (value: boolean) => void;
}
interface MainLayoutProps {
children: React.ReactNode;
}
const MainLayoutContext = React.createContext<MainLayoutContextValue>({
isShowCart: false,
setIsShowCart: () => {},
});
const MainLayoutProvider = ({ children }: MainLayoutProps) => {
const [isShowCart, setIsShowCart] = useState(false);
const contextValue = React.useMemo(
() => ({
isShowCart,
setIsShowCart,
}),
[isShowCart, setIsShowCart]
);
return (
<MainLayoutContext.Provider value={contextValue}>
{children}
</MainLayoutContext.Provider>
);
};
const useMainLayoutContext = () => {
const popups = useContext(MainLayoutContext);
if (popups == null) {
throw new Error(
"useMainLayoutContext() called outside of a PopUpProvider?"
);
}
return popups;
};
export { MainLayoutProvider, useMainLayoutContext };
- và chúng ta có thể lấy và đẩy giá trị isShowCart bằng câu lệnh sau đây ở bất cứ đâu:const { isShowCart, setIsShowCart } = useMainLayoutContext();