인프런 커뮤니티 질문&답변

현진님의 프로필 이미지
현진

작성한 질문수

처음 만난 리액트(React)

(실습) styled-components를 사용하여 스타일링 해보기

styled-components

작성

·

1.6K

0

chapter 15 실습에서 막힙니다.

styled-components를 @latest 붙여서 다운받았는데도 실행이 안됩니다.

그냥 빈 하얀 화면만 뜹니다...

다른 챕터는 확인해보니까 다 되던데, 왜 styled-components 실습만 왜 안될까요?

Blocks.jsx 파일 코드

import styled from "styled-components";

const Wrapper = styled.div`
  padding: 1rem;
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: flex-start;
  background-color: lightgrey;
`;

const Block = styled.div`
  padding: ${(props) => props.padding};
  border: 1px solid black;
  border-radius: 1rem;
  background-color: ${(props) => props.backgroundColor};
  color: white;
  font-size: 2rem;
  text-align: center;
`;

const blockItems = [
  {
    label: "1",
    padding: "1rem",
    backgroundColor: "red",
  },
  {
    label: "2",
    padding: "3rem",
    backgroundColor: "green",
  },
  {
    label: "3",
    padding: "2rem",
    backgroundColor: "blue",
  },
];

function Blocks(props) {
  return (
    <Wrapper>
      {blockItems.map((blockItem) => {
        return (
          <Block
            padding={blockItem.padding}
            backgroundColor={blockItem.backgroundColor}
          >
            {blockItem.label}
          </Block>
        );
      })}
    </Wrapper>
  );
}

export default Blocks;

index.js 파일 코드

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

// import Library from "./chapter_03/Library";
// import Clock from "./chapter_04/Clock";
// import CommentList from "./chapter_05/CommentList";
// import NotificationList from "./chapter_06/NotificationList";
// import Accomodate from "./chapter_07/Accommodate";
// import ConfirmButton from "./chapter_08/ConfirmButton";
// import LandingPage from "./chapter_09/LandingPage";
// import AttendanceBook from "./chapter_10/AttendanceBook";
// import SignUp from "./chapter_11/SignUp";
// import Calculator from "./chapter_12/Calculator";
// import ProfileCard from "./chapter_13/ProfileCard";
// import DarkOrLight from "./chapter_14/DarkOrLight";
import Blocks from "./chapter_15/Blocks";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <Blocks />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

빈 하얀 화면에서 F12 눌러서 오류 확인해보니까 이렇게 뜹니다.

Warning: Each child in a list should have a unique "key" prop.

Check the render method of Blocks. See https://reactjs.org/link/warning-keys for more information.

at O (http://localhost:3000/static/js/bundle.js:43804:6)

at Blocks

printWarning @ react-jsx-dev-runtime.development.js:87

2react.development.js:209 Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

1. You might have mismatching versions of React and the renderer (such as React DOM)

2. You might be breaking the Rules of Hooks

3. You might have more than one copy of React in the same app

See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

printWarning @ react.development.js:209

react.development.js:1618 Uncaught TypeError: Cannot read properties of null (reading 'useContext')

at Object.useContext (react.development.js:1618:1)

at StyledComponent.ts:124:1

at O (StyledComponent.ts:190:1)

at renderWithHooks (react-dom.development.js:16305:1)

at updateForwardRef (react-dom.development.js:19226:1)

at beginWork (react-dom.development.js:21636:1)

at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)

at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)

at invokeGuardedCallback (react-dom.development.js:4277:1)

at beginWork$1 (react-dom.development.js:27451:1)

2react.development.js:209 Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

1. You might have mismatching versions of React and the renderer (such as React DOM)

2. You might be breaking the Rules of Hooks

3. You might have more than one copy of React in the same app

See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

printWarning @ react.development.js:209

react.development.js:1618 Uncaught TypeError: Cannot read properties of null (reading 'useContext')

at Object.useContext (react.development.js:1618:1)

at StyledComponent.ts:124:1

at O (StyledComponent.ts:190:1)

at renderWithHooks (react-dom.development.js:16305:1)

at updateForwardRef (react-dom.development.js:19226:1)

at beginWork (react-dom.development.js:21636:1)

at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)

at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)

at invokeGuardedCallback (react-dom.development.js:4277:1)

at beginWork$1 (react-dom.development.js:27451:1)

react-dom.development.js:18687 The above error occurred in the <styled.div> component:

at O (http://localhost:3000/static/js/bundle.js:43804:6)

at Blocks

Consider adding an error boundary to your tree to customize error handling behavior.

Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

logCapturedError @ react-dom.development.js:18687

react-dom.development.js:26923 Uncaught TypeError: Cannot read properties of null (reading 'useContext')

at Object.useContext (react.development.js:1618:1)

at StyledComponent.ts:124:1

at O (StyledComponent.ts:190:1)

at renderWithHooks (react-dom.development.js:16305:1)

at updateForwardRef (react-dom.development.js:19226:1)

at beginWork (react-dom.development.js:21636:1)

at beginWork$1 (react-dom.development.js:27426:1)

at performUnitOfWork (react-dom.development.js:26557:1)

at workLoopSync (react-dom.development.js:26466:1)

at renderRootSync (react-dom.development.js:26434:1)

 

뭐가 문제일까요?

답변 1

0

Inje Lee (소플)님의 프로필 이미지
Inje Lee (소플)
지식공유자

안녕하세요, 소플입니다.

먼저 첫 번째 Warning은 map() 함수를 사용해서 리스트를 렌더링 할 때 Blockkey가 빠져있어서 나오는 것입니다.

관련해서 자세한 설명은 아래 링크를 참고하시기 바랍니다.

https://www.frontoverflow.com/question/12/Each%20child%20in%20a%20list%20should%20have%20a%20unique%20%E2%80%9Ckey%E2%80%9D%20prop.

 

그리고 또 다른 에러로 Invalid hook call이 나와 있는데,

이 부분은 아무래도 styled-components를 설치하면서 뭔가 꼬인 것 같습니다.

먼저 VS Code를 껐다가 다시 켜서 실행해보시고,

그래도 안 되면 node_modules 폴더 전체를 삭제한 이후에 다시 npm install을 해서 해보시기 바랍니다.

 

만약 계속 에러가 수정되지 않으면,

작성하신 코드를 GitHub public repository에 올려주시고 저에게 링크를 남겨주시면 좋을 것 같습니다!

 

감사합니다.

현진님의 프로필 이미지
현진

작성한 질문수

질문하기