How to use context in layout when we have two separate layouts in next.js?

Viewed 48

I use two separate layouts in NextJS. When I call the context like this, I have access to the values in the children of the layout, but I don't have access to the layout, and the context return undefined.

it is my context:

import React from "react";

export const AuthContext = React.createContext();

_app.js:

function MyApp({Component, pageProps}) {
    const getLayout = Component.getLayout || ((page) => page)
    const [state, setState] = useState('')

    return getLayout(
        <AuthContext.Provider value={{
            state,
            setState
        }}>
            <Component {...pageProps} />
        </AuthContext.Provider>
    )

}

export default MyApp

I add this code in every page to use layout one or layout two

index.getLayout = function getLayout(page) {
    return (
        <Layout1>
            {page}
        </Layout1>
    )
}
1 Answers

i change app.js:

return (
        <AuthContext.Provider value={{
            auth,
            dispatch
        }}>
            {getLayout(<Component {...pageProps} />)}
        </AuthContext.Provider>
    )

Because the layout was not in context

Related