본문 바로가기

Work/React

[NextJs] Router

Next Js에서 Query로 넘긴 값을 다음 Page에서 Prop으로 사용하기

1.이전 페이지에서 넘기기

const router = useRouter()
router.push({pathname: "/path", query: {test: "hello"}}, "/path")

첫번째 param: {pathname: "/path", query: {test: "hello"}}

path와 넘기고자 하는 정보를 정의한다.

 

두번째 param: "/path" ... as

query로 넘기게 되면 Url이 길어지게 되는데, 바꾸고자 하는 정보를 적어 준다. 즉, 브라우저 URL로 표시 하고 싶은 경로를 정의한다.

 

2. 받는 page에서 

const router = useRouter()
const {query: {test}} = router

혹은 

SentPage.getInitialProps = ({query: {test}}) => {
    return {test}
}

export default SentPage(props){
    const [values, setValues] = React.useState(props)
    
    {values.test} <-- 이렇게 이용 가능
}

 

 

[참조]

https://www.freecodecamp.org/news/routing-in-nextjs-beginners-guide/