[React] 시계 만들기
현재 시간을 표시해주는 element를 만들어보자!
import React from "react";
function Clock(props) {
return (
<div>
<h1>Hi, React!</h1>
<h2>현재 시간: {new Date().toLocaleTimeString()}</h2>
</div>
);
}
export default Clock;
1. Clock.jsx 파일을 만들고, 현재 시간을 알려주는 컴포넌트를 만든다
import Clock from './chap_04/Clock';
setInterval(() => {
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Clock />);
}, 1000);
2. index.js 파일에
1000ms마다 새롭게 Clock 컴포넌트를 root에 랜더링하도록 하는 코드를 추가한다
npm start를 하다가 만난 첫 번째 에러
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /Users/yeonsu/Desktop/React-Study-main/practice-jsx/package.json
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/Users/yeonsu/Desktop/React-Study-main/practice-jsx/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/yeonsu/.npm/_logs/2022-08-08T03_55_52_395Z-debug-0.log
💡 해결방법: package.json이 있는 폴더로 경로를 이동한다
cd "경로"
나같은 경우는 똑같은 이름의 폴더가 2개나 있어서 첫 번째 폴더의 경로에서 npm start를 하려고 하니까 나타났던 에러였다.
npm start를 하다가 만난 두 번째 에러
Uncaught TypeError: react_dom_client__WEBPACK_IMPORTED_MODULE_1__.render is not a function
at index.js:11:1
강의가 예전꺼다 보니까 React version이 18로 업데이트 되면서 더이상 ReactDOM.render을 지원하지 않아 생기는 문제였다.
setInterval(() => {
ReactDOM.render(
<React.StricMode>
<Clock />
</React.StricMode>,
document.getElementById('root')
);
}, 1000);
👆예전 방식 코드를
setInterval(() => {
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Clock />);
}, 1000);
👆이런 식으로 수정해주면 된다