Nevin
Nevin

Reputation: 375

React/Nextjs - know what page is rendered on _app.js

So I'm trying to render my web nav and footer on my _app.js . I wanted to dynamically change the style of my nav/footer depending on the page being accessed. I thought about putting the nav and footer to the individual pages instead but i don't think it's best practice.

How do I know what page im accesing inside _app.js

ex.

pages/index.js
pages/profile.js

in my _app.js i will change the style of nav and footer depending on the page accesed.

Upvotes: 1

Views: 3028

Answers (3)

Phill
Phill

Reputation: 21

You can use the useRouter hook which has an attribute asPath.

import { useRouter } from "next/router";

const path = useRouter().asPath;

You can then use this value to change content of pages/_app.tsx based on page

Upvotes: 2

ekocibar
ekocibar

Reputation: 149

You may use the document object.

const [url, setUrl] = useState('')

useEffect(() => {
  setUrl(document.URL)
}, [document.URL])

Upvotes: 0

thortsx
thortsx

Reputation: 2280

I think you can based on Router.pathName in Nextjs to change the style of nav and footer like this:

const get firstPathName = pathName => pathName.split("/")[1]
export default class extends React.Component {
  getInitialProps ({ pathname, query }) {
    switch(firstPathName(pathname)) {
       case "":
       case "index": // style nav and footer with index.js
         break;
       case "profile": // style nav and footer with profile.js
         break;
       default: // do with default 
         break;
    }
  }
}

See this PR to more information: Add pathname and query to the argument of getInitialProps


EDIT

In your case, My suggest is connect to Redux and save current url at level Component into store. Then, in _app.js, you will get this to handle style nav or footer. Example:

At Component:

const connectToRedux = connect(null, dispatch => ({
   changeCurrentUrl: () => dispatch({ 
       type: "CHANGE_CURRENT_URL", payload: firstPathName(Router.pathName)
   })
}))
componentWillMount() {
   if (process.browser) { // make sure isClient in Nextjs
       this.props.changeCurrentUrl()
   }
}

At Reducer:

export default {
   currentUrl: (state = "", action) => {
      if (action.type === "CHANGE_CURRENT_URL") {
          state = action.payload;
      }
      return state;
   }
}

At app.js // make sure connected to Redux at here

componentWillMount() {
   const { currentUrl } = this.props
   // handle style nav and footer here depending on url
}

Upvotes: 0

Related Questions