codestates / codestates/BanThing

[Error Handling] TypeError : Cannot read properties of null (reading 'style')

Open
#67 1 comment 0 reactions 1 assignee Claimed by @slight-snow View on GitHub
client error solved
Dominant language
TypeScript
Stars
0
Forks
2
PR merge metrics
No merged PRs in 30d

Description

### 어떤 에러인가요?
- Unhandled Runtime Error
TypeError : Cannot read properties of null (reading 'style')
```javascript
var scrolled = (winScroll / height) * 100;
const myBar = document.getElementById("myBar") as HTMLParagraphElement;
myBar.style.width = scrolled + "%";
^
```

### 에러 핸들링 방법
해당 에러를 Scroll Indicator(Progress Bar) 컴포넌트를 개발하면서 발견하게 됐다.
`progress.tsx` 컴포넌트 파일 내에는

```javascript




```

위와 같은 return 이 작성되어 있었고, progress.tsx 파일은 index.tsx (Landing Page) 에만 Progress 로 import 되어있었다.
main.tsx (Main Page) 에는 progress.tsx 가 일절 import 되지 않았다.
하지만 어째서인지 Landing Page 에서는 정상적으로 컴포넌트가 작동하는 것을 확인할 수 있었으나,
Main Page 에서 TypeError 문구가 나타났다.

```javascript
const myBar = document.getElementById("myBar") as HTMLParagraphElement;
console.log(myBar)
```

위의 코드와 같이 `console.log(myBar)` 를 통해 console 창을 확인해보니,
Landing Page 에서는 정상적으로 myBar 의 코드가 찍히는 한편, Main Page 에서는 null 로 찍혔다.
myBar 가 null 값이라 style 을 읽어오는데서 에러가 발생한 것이다.
 
Main Page 에는 컴포넌트로 넣어두지 않았는데 왜 console 이 찍히는건지 정확히는 알 수 없으나,
Next.js 에 내장되어 있는 Link 를 통해 페이지를 렌더링하다보니 각 페이지마다 새 페이지가 렌더링 되는 개념이 아니라
동시에 내장되어 작동하기 때문인 것으로 추정된다.

이에 따라 if 문을 통해 조건문을 작성해주었다.

```javascript
const myBar = document.getElementById("myBar") as HTMLParagraphElement;
if (myBar !== null) {
myBar.style.width = scrolled + "%";
}
```

이렇게 작성해주니 Landing Page 에서는 정상적으로 Scroll Indicator 가 보이고,
Main Page 에서는 더 이상 TypeError 가 발생하지 않았다 :)

#### TypeError 가 발생한다면 console.log 를 찍어서 확인해보는 습관을 들이자!
 

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.