Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get URL pathname in nextjs

I have a signin page and layout component.Layout component has header.I don't want to show header in signin .and for that I want to get url pathname.based on pathname show the header .

import * as constlocalStorage from '../helpers/localstorage'; import Router from 'next/router';  export default class MyApp extends App {     componentDidMount(){         if(constlocalStorage.getLocalStorage()){             Router.push({pathname:'/app'});         } else{             Router.push({pathname:'/signin'});         }      }      render() {         const { Component, pageProps } = this.props         return ( //I want here pathname for checking weather to show header or not                 <Layout>                     <Component {...pageProps} />                 </Layout>         )     } } 

please help

like image 328
Karthi Avatar asked Sep 20 '19 05:09

Karthi


People also ask

How do I get page URL or hostname in NextJS project?

You need to ensure your access to window. location. hostname happens on the client-side only, and not during server-side rendering (where window does not exist). You can achieve that by moving it to a useEffect callback in your component.

What is NextPage in NextJS?

NextPage is a type exported by NextJS. When we write Page: NextPage we're saying that our Page component is of type NextPage . Follow this answer to receive notifications.

How do I redirect on NextJS?

To redirect from / to another page with Next. js, we can get the pathname property from the Router object and do the redirect if pathname is '/' . import React, { useEffect } from "react"; import Router from "next/router"; const Comp = () => { //...


1 Answers

If you want to access the router object inside any functional component in your app, you can use the useRouter hook, here's how to use it:

import { useRouter } from 'next/router'  export default function ActiveLink({ children, href }) {   const router = useRouter()   const style = {     marginRight: 10,     color: router.pathname === href ? 'red' : 'black',   }    const handleClick = e => {     e.preventDefault()     router.push(href)   }    return (     <a href={href} onClick={handleClick} style={style}>       {children}     </a>   ) } 

If useRouter is not the best fit for you, withRouter can also add the same router object to any component, here's how to use it:

import { withRouter } from 'next/router'  function Page({ router }) {   return <p>{router.pathname}</p> }  export default withRouter(Page) 

https://nextjs.org/docs/api-reference/next/router#userouter

like image 72
imjared Avatar answered Sep 23 '22 22:09

imjared