다크모드 GlobalStyle 적용하기 : [Cannot read properties of undefined (reading 'body'), The above error occurred in the <l2> component]

2024. 8. 29. 19:54·Programming/React

리액트에서 useState, useEffect를 주로 다루다보니,

다른 Hook도 잘 활용하고 싶은 마음에 여러 가지를 시도하고 있는 요즘은 useContext로 '다크모드'를 다루는 와중에..

 

ThemeContext 파일을 따로 생성하여 전역 객체로 다룰 수 있도록 설정해주고,

useContext 훅을 사용하여, styled-component에 다크모드를 적용하고 있었다.

뒷배경에도 다크모드를 적용해야 했기에, 초기에 설정해둔 GlobalStyle 수정 중에 에러가 발생했다.

 

Cannot read properties of undefined (reading 'body')

The above error occurred in the <l2> component

 

다크모드로 설정해둔 객체를 읽지 못하여, 컴포넌트 렌더링이 안되고 있었다.

렌더링 실패

처음 써본 개념을 프로젝트에 적용하다가 에러가 생길 때, 참 헤매기 쉬운 상황이다..

 

[기존 코드]

import { createGlobalStyle } from "styled-components";
import reset from "styled-reset";

const GlobalStyle = createGlobalStyle`
${reset};

body {
    display: flex;
    height : 100vh;
    margin: auto;
    font-family: 'Noto Sans KR', sans-serif;
    font-weight: 400;
    font-size: 1.5em;
    justify-content: center;
    background: ${({ theme }) => theme.body};
}
`;
export default GlobalStyle;

문제와 원인

1. 초기 렌더링 시, theme 정의가 되지 않았다. 그래서 undefined를 반환했다.

2. React 컴포넌트는 처음 렌더링 시점에 상태가 비동기로 처리되기 때문에 상태가 완전히 전달되지 않을 수 있다.

 

해결 방법

1. theme?.body와 같이 옵셔널 체이닝을 사용하여 theme 객체가 undefined인 경우에도 에러가 발생하지 않도록 한다.

2. undefined가 반환되는 경우 초기값을 설정해두고, undefined 대신 초기값(#ffffff)이 실행되도록 한다.

 

[수정 코드]

import { createGlobalStyle } from "styled-components";
import reset from "styled-reset";

const GlobalStyle = createGlobalStyle`
${reset};

body {
    display: flex;
    height : 100vh;
    margin: auto;
    font-family: 'Noto Sans KR', sans-serif;
    font-weight: 400;
    font-size: 1.5em;
    justify-content: center;
    background: ${({ theme }) => theme?.body || "#ffffff"};
}
`;
export default GlobalStyle;

 

적용 성공

 

이제 해결이 되었으니,, localStorage에 저장해서 새로고침을 해도 풀리지 않도록 설정해야겠다!

'Programming > React' 카테고리의 다른 글

카카오 소셜 로그인  (4) 2024.09.15
AWS S3로 프론트엔드 배포하기  (0) 2024.09.07
chart.js React에 적용하기  (0) 2024.08.21
단일 Modal 컴포넌트 props 사용해서 수입/지출 내역 관리하기 [Warning: React does not recognize the modalColor prop on a DOM element.]  (0) 2024.08.17
Modal 생성 후 배경 Blur 처리 하기  (0) 2024.08.04
'Programming/React' 카테고리의 다른 글
  • 카카오 소셜 로그인
  • AWS S3로 프론트엔드 배포하기
  • chart.js React에 적용하기
  • 단일 Modal 컴포넌트 props 사용해서 수입/지출 내역 관리하기 [Warning: React does not recognize the modalColor prop on a DOM element.]
gitit
gitit
짬내서 쓰는 프론트엔드와 기술 메모 공간
  • gitit
    깃잇-gitit
    gitit
  • 전체
    오늘
    어제
    • 분류 전체보기
      • Coding Test
        • Programmers
        • BackJoon
      • Development Tools
        • Firebase
        • Git
        • Monorepo
      • Programming
        • JavaScript
        • React
        • React-Native
      • etc.
        • GeekNews
        • Blockchain
      • Technical Interview
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    파이어베이스
    node.js
    자바스크립트
    kakao
    AWS
    코딩테스트
    리액트
    개발
    백준
    코테
    알고리즘
    styled-components
    파이썬
    frontend
    React
    코딩
    프로그래머스
    js
    긱뉴스
    독학
    기술 질문
    기본문법
    Firebase
    BFS
    javascript
    S3
    매일메일
    modal
    프론트엔드
    geeknews
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
gitit
다크모드 GlobalStyle 적용하기 : [Cannot read properties of undefined (reading 'body'), The above error occurred in the <l2> component]
상단으로

티스토리툴바