next/router 사용하기

next/router 사용하기


next/router 사용하기

router 객체에 접근하기 위해서 useRouter를 사용한다

1. import 후

import { useRouter } from "next/router";

2. 아래의 형태로 사용

const router = useRouter()

router object

1. asPath

asPath = '/501da229-9915-4264-9d37-6783545ee553'

2. basePath

  • 활성화 되어 있는 basePath → next.config.js에 지정한 경로 접두사
// next.config.js
module.exports = {
  basePath: '/경로접두사',
}
 

3. isFallback

  • fallback 에 관련된 값 boolean 또는 'blocking'으로 들어옴

→ 빌드 타임에 생성해놓지 않은 path로 요청이 들어온 경우 어떻게 할지 정하는 부분

⚠️ fallback 관련 내용 참고https://velog.io/@mskwon/next-js-static-generation-fallback#fallback

4. isReady

  • 라우터 필드가 클라이언트 측에서 업데이트되고 사용할 준비가 되었는지 여부.

→ useEffect 메소드 내에서만 사용해야하며 서버에서 조건부로 렌더링 하는 데에 사용해야한다.

⚠️ isReady 사용 예시https://im-designloper.tistory.com/98

5. isPreview

  • 현재 미리보기 모드인지 여부

6. pathname

  • 활성화 되어 있는 basePath → next.config.js에 지정한 경로 접두사

7. query

현재 route값 → /pages폴더 하위에 있는 페이지 경로

router.push | router.replace

클라이언트에서 페이지 전환을 할때 사용

push로 이동시키면 history stack에 쌓여서 뒤로가기가 가능하고replace로 이동시키면 history stack에 안쌓여서 뒤로가기 불가능

router.push(url, as, options) | router.replace(url, as, options)

⚠️

외부 url로 이동하는 경우

1. url

  • 이동할 url > url 객체 사용 가능

2. as

  • 이동 후 브라우저에 표시될 URL

3. option

scroll: default: true 탐색 후 페이지 맨 위로 스크롤 제어 shallow: default: false getStaticProps, getServerSideProps, getInitialProps를 다시 실행하지 않고 현재 페이지 경로 업데이트 locale: 새로운 페이지의 locale}

// as 사용 안하고 option (scroll) 사용하는 경우 예제
router.push(
  {
    pathname: router.pathname,
    query: { ...router.query, currency: newCurrency.value },
  },
  undefined,
  { scroll: false }
);

router.prefetch

빠른 클라이언트 전환을 위해 페이지를 데이터를 미리 가져온다.

next/link 의 경우 자동으로 페이지를 미리 가져오기 때문에 next/link 가 없는 탐색에서 유용하다.

router.prefetch(url, as)

1. url

  • 이동할 url > url 객체 사용 가능

2. as

  • 이동 후 브라우저에 표시될 URL

router.beforePopState

라우터가 동작하기전에 무언가 작업을 하고 싶을 때 사용

import { useEffect } from "react";
import { useRouter } from "next/router";
 
export default function Page() {
  const router = useRouter();
 
  useEffect(() => {
    router.beforePopState(({ url, as, options }) => {
      // 아래 두 url로만 이동을 허용하고 싶을때
      if (as !== "/" && as !== "/other") {
        // Have SSR render bad routes as a 404.
        window.location.href = as;
        return false;
      }
 
      return true;
    });
  }, []);
 
  return <p>Welcome to the page</p>;
}

router.back

뒤로가기 버튼 클릭과 같음

window.history.back() 실행

import { useRouter } from "next/router";
 
export default function Page() {
  const router = useRouter();
 
  return (
    <button type="button" onClick={() => router.back()}>
      Click here to go back
    </button>
  );
}

router.reload

새로고침 버튼 클릭과 같음

window.history.reload() 실행

import { useRouter } from "next/router";
 
export default function Page() {
  const router = useRouter();
 
  return (
    <button type="button" onClick={() => router.reload()}>
      Click here to reload
    </button>
  );
}

router.events

next/router로 이벤트를 감지해서 특정 이벤트가 발생하면 함수를 실행

  1. routeChangeStart
routeChangeStart(url, { shallow }) 경로가 변경되기 시작할때 발생
  1. routeChangeComplete
routeChangeComplete(url, { shallow }) 경로가 완전히 변경되면 발생
  1. routeChangeError
routeChangeError(url, { shallow }) 경로 변경시 오류가 발생하거나 경로 전환 취소시 발생 (err.cancelled - 탐색이 취소되었는지 여부)
  1. beforeHistoryChange
beforeHistoryChange(url, { shallow }) 브라우저의 history를 변경하기 전에 발생
  1. hashChangeStart
hashChangeStart(url, { shallow }) 해시는 변경되지만 페이지는 변경되지 않을때 발생
  1. hashChangeComplete
hashChangeComplete(url, { shallow }) 해시가 변경되었지만 페이지는 변경되지 않을때 발생
import { useEffect } from 'react'
import { useRouter } from 'next/router'
 
export default function MyApp({ Component, pageProps }) {
  const router = useRouter()
 
  useEffect(() => {
    const handleRouteChange = (url, { shallow }) => {
      console.log(
        `App is changing to ${url} ${
          shallow ? 'with' : 'without'
        } shallow routing`
      )
    }
 
    router.events.on('라우터이벤트 이름 ex) routeChangeStart' handleRouteChange)
 
    // If the component is unmounted, unsubscribe
    // from the event with the `off` method:
    return () => {
      router.events.off('라우터이벤트 이름 ex) routeChangeStart' handleRouteChange)
    }
  }, [])
 
  return <Component {...pageProps} />
}

withRouter

라우터에 의해서 호출된 컴포넌트가 아니어도 match, location, history 객체에 접근할 수 있도록 해준다.

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

+ widthRouter > use TypeScript

import React from "react";
import { withRouter, NextRouter } from "next/router";
 
interface WithRouterProps {
  router: NextRouter;
}
 
interface MyComponentProps extends WithRouterProps {}
 
class MyComponent extends React.Component<MyComponentProps> {
  render() {
    return <p>{this.props.router.pathname}</p>;
  }
}
 
export default withRouter(MyComponent);

✔️ 참고

https://im-designloper.tistory.com/102