DEV Community

moezguedri
moezguedri

Posted on

nextjs: Listen to Layout events within pages

Is having a global state [callable, setCallable] a good design to make pages listen to Layout events.
Example:
We can have a button Print in the AppBar of the layout MyLayout.
Then, each page calls setCallable({ print: () => alert('print me') }).

/* _app.tsx */
import "../styles/globals.css";
import type { AppProps } from "next/app";
import MyLayout from "../components/MyLayout";
import { useState } from "react";

function MyApp({ Component, pageProps }: AppProps) {
  const [callable, setCallable] = useState();
  return (
      <MyLayout callable={callable}>
        <Component {...pageProps} setCallable={setCallable} />
      </MyLayout>
  );
}

export default MyApp;
Enter fullscreen mode Exit fullscreen mode
/* MyLayout.tsx */
export default function MyLayout({ children, callable }) {
  return (
    <>
      <AppBar position="fixed" open={open}>
        <Toolbar>
          {callable?.print && (
            <IconButton onClick={callable.print}>
              <Print />
            </IconButton>
          )}
          {/*Other buttons to call other callbacks can be added here*/}
        </Toolbar>
      </AppBar>
      <main>{children}</main>
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode
/* MyPage.tsx */
export default function MyPage(props: any) {
  useEffect(() => {
    props.setCallable?.({
      print: () => alert("print the current page"),
      /* Other callbacks can be added here */
    });
  }, []);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)