Zakaria
Zakaria

Reputation: 440

Nextjs - passing props from custom _app.js to <Navbar> component?

How can I pass props from here to a Navbar component that I would add under the Head component? I already did it in the index.js page using getServerSideProps, but it doesn't seem to work in the _app.js file.

import "../_app.css";

import React from "react";
import PropTypes from "prop-types";
import Head from "next/head";
import { ThemeProvider } from "@material-ui/core/styles";
import CssBaseline from "@material-ui/core/CssBaseline";
import theme from "../theme";

export default function MyApp({ Component, pageProps }) {
    React.useEffect(() => {
        // Remove the server-side injected CSS.
        const jssStyles = document.querySelector("#jss-server-side");
        if (jssStyles) {
            jssStyles.parentElement.removeChild(jssStyles);
        }
    }, []);

    return (
        <React.Fragment>
            <Head>
                <title>Furnibnz | Baldai Internetu ir Nemokamas Pristatymas</title>
                <meta
                    name="viewport"
                    content="minimum-scale=1, initial-scale=1, width=device-width"
                />
            </Head>
            <ThemeProvider theme={theme}>
                {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
                <CssBaseline />
                <Component {...pageProps} />
            </ThemeProvider>
        </React.Fragment>
    );
}

MyApp.propTypes = {
    Component: PropTypes.elementType.isRequired,
    pageProps: PropTypes.object.isRequired,
};

Is there a better way to use a Navbar Component in every page or is this this the right way?

Upvotes: 5

Views: 4912

Answers (1)

Zakaria
Zakaria

Reputation: 440

Good times when this was my biggest problem lol

For whoever really needs an answer to this:

You can't currently use getStaticProps and getServerSideProps in the _app component, so if I'm not wrong I was trying to fetch initial data (probably categories list) and pass it to a component. To fetch initial data at _app level, you should use getInitialProps (NextJs developers suggest to avoid using this), but be aware that using it, will stop NextJs from automatically statically optimize the pages that do not rely on any kind of fetching method (they will be server-side rendered - even a simple "about us" page that could be served as static html otherwise)

You can read more about it here: https://nextjs.org/docs/api-reference/data-fetching/getInitialProps

Upvotes: 2

Related Questions