To customize the navigation and footer styles in Next.js based on Router.pathname, you can implement the following approach:
const getFirstPathName = pathname => pathname.split("/")[1]
export default class CustomStyle extends React.Component {
static async getInitialProps ({ pathname, query }) {
switch(getFirstPathName(pathname)) {
case "":
case "index": // style nav and footer for index.js
break;
case "profile": // style nav and footer for profile.js
break;
default: // handle default styling
break;
}
}
}
You can refer to this Pull Request for additional details: Add pathname and query to the argument of getInitialProps
UPDATE
In your situation, I recommend utilizing Redux
to store the current URL at a higher component level. In the _app.js
, you can then access this information to manage the navigation and footer styles accordingly. Here's an example:
Within the Component:
const ConnectedComponent = connect(null, dispatch => ({
changeCurrentUrl: () => dispatch({
type: "CHANGE_CURRENT_URL", payload: getFirstPathName(Router.pathname)
})
}))
componentWillMount() {
if (process.browser) { // ensure it is Client-side rendering in Next.js
this.props.changeCurrentUrl()
}
}
Within the Reducer:
export default {
currentUrl: (state = "", action) => {
if (action.type === "CHANGE_CURRENT_URL") {
state = action.payload;
}
return state;
}
}
In app.js
// ensure connection to Redux is established here
componentWillMount() {
const { currentUrl } = this.props
// adjust navigation and footer styles based on the URL here
}