본문 바로가기
Front/React

[React] 시계 만들기

by 오엥?은 2023. 4. 14.
반응형

 

  • 현재 시간을 출력하는 간단한 Clock 컴포넌트
import React from "react";

function Clock(props) {
    return (
        <div>
            <h1>안녕, 리액트!</h1>
            <h2>현재 시간: {new Date().toLocaleTimeString()}</h2>
        </div>
    );
}

export default Clock;

 

  • 만든 Clock 컴포넌트를 화면에 랜더링하기 위해 index.js 를 수정한다.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

import Library from './chapter_03/Library';
import Clock from './chapter_04/Clock';

setInterval( () => {
  ReactDOM.render(
    <React.StrictMode>
      <Clock />
    </React.StrictMode>,
    document.getElementById('root')
  );
}, 1000);

// 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();

setInterval 함수를 사용하여 1000ms 마다 새로운 Clock 컴포넌트를 root div 에 새롭게 랜더링되도록 만들었다.

 

  • npm start

개발자 도구를 열어보면 시간이 깜빡이면서 바뀌는 것을 볼 수 있다.

반응형

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

[React] Component 생성 / 렌더링 / 합성과 추출  (0) 2023.04.14
[React] Components and Props  (0) 2023.04.14
[React] Elements  (0) 2023.04.14
[React] JSX 코드 작성  (0) 2023.04.14
[React] JSX 사용법  (0) 2023.04.13