next.js
Next.js 에서 반응형(Responsive) 작업하기 (window is not defined)
이챙(leechaeng)
2022. 1. 14. 14:52
Next.js 에서 window.innerWidth 값 구하다 window is not defined 오류 발생!
서버사이드 렌더링 할때 서버엔 window , document 객체가 없기 때문에 발생하는 오류이다.
그래서 useEffect or componentDidMount 에서 사용해주어야 한다.
const Project = () => {
const [windowWidth, setWindowWidth] = useState(0)
// resize 될때만 함수 불러오기
let timer
const resizeWindow = () => {
clearTimeout(timer)
timer = setTimeout(() => {
// 현재 window width 값
setWindowWidth(window.innerWidth)
}, 500)
}
useEffect(() => {
setWindowWidth(window.innerWidth)
window.addEventListener("resize", resizeWindow)
return () => {
window.removeEventListener("resize", resizeWindow)
}
}, [windowWidth])
return (<div className={windowWidth >= 1023 ? "on" : ""}>test..</div>)
}
export default Project
간단하게 사용할 수 있는 코드다.
resize가 최종적으로 계산 되었을때만 window width 값을 찍어내기 위해 setTimeout 을 추가했다.
개인적으로 hooks로 따로 빼면 좋을 듯 한데 나중에 추가하도록 하겠다.
반응형