프론트엔드 웹/Next

외부 URL에 새창으로 이동하기 (useRouter, window.location, window.open)

세리둥절 2022. 6. 28. 16:07
반응형

 

✔️ 필요성

Next.js에서 어떤 버튼을 눌렀을 때 외부 URL에 새 창(new tab)으로 이동하고 싶다.

 

 

 

 

✔️ 문제 확인

처음에는 next/router의 useRouter를 사용했는데 새 창으로 이동이 안 된다.

 import { useRouter } from "next/router";
 
 const href = '이동하고자 하는 URL'

 const router = useRouter();
  const onPress = () => {
    router.push(href);
  };

 

공식 문서를 보니 external URL에는 router.push 보다 window.location이 적절하다고 한다.

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

 

next/router | Next.js

Learn more about the API of the Next.js Router, and access the router instance in your page with the useRouter hook.

nextjs.org

 

 

 

시킨대로 window.location.href 를 사용했는데 이번에도 새 창으로 띄워지지는 않는다.

const onPress = () => {
    window.location.href = href;
};

 

 

 

✔️ 문제 해결

좀 더 찾아보니 새 창을 띄울 때에는 window.open을 사용하면 된다고 한다.

const onPress = () => {
    window.open(href);
};

훨씬 코드도 깔끔한 것 같다!

반응형

'프론트엔드 웹 > Next' 카테고리의 다른 글

Next.js API Router로 Chart.js 이미지 리턴하기  (0) 2023.05.16
[Next] Next.13에서 API Route 사용하기  (0) 2023.05.08
openssl로 Next.js HTTPS 적용하기  (0) 2022.04.28
Nginx  (0) 2022.04.28
Next.js SWR 예제  (0) 2022.03.24