3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【初学者向け】Reactで世界時計を作ってみた

Last updated at Posted at 2020-03-14

learn-react.jpg

背景

「React勉強し始めた」「Reactで簡単に動くものを作ってみたい」という方向けに、『世界時計』を作ってみました。

JavaScriptで時計を作る記事はよく見かけますが、Reactで作っている記事は見つからなかったので、初学者の参考になればと思っています。

デモ

worldclock.gif

仕様

  • 初期表示は、東京の時間が表示されている
  • セレクトボックスで国を選ぶと、画面遷移が起きずに時刻が変わる

※サマータイムは考慮していません。

コード

App.js
import React, { Component } from 'react'

import Selectbox from './components/Selectbox'
import Clock from './components/Clock'

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      timelag: '',
      nowTime: ''
    }
  }

  // コンポーネントがマウントされた後に実行
  componentDidMount() { // ----------- ①
    setInterval(() => {
      this.setState({
        nowTime: this.getTime(this.state.timelag)
      });
    }, 1000)
  }

  // 日付と時刻を取得する(ex. 2020年 3月 14日 12:00:00)
  getTime(timelag = 0) {
    let japanTime = new Date().getTime()
    let nowTime = new Date(japanTime + timelag*60*60*1000)
    let year = nowTime.getFullYear()
    let month = nowTime.getMonth() + 1
    let date = nowTime.getDate()
    let hours = nowTime.getHours()
    let minutes = nowTime.getMinutes()
    let seconds = nowTime.getSeconds()

    if (hours < 10) hours = `0${hours}`
    if (minutes < 10) minutes = `0${minutes}`
    if (seconds < 10) seconds = `0${seconds}`

    const time = `${year}${month}${date}${hours}:${minutes}:${seconds}`
    return time
  }

  doChange = (e) => { // ----------- ②
    e.preventDefault()
    this.setState({
      timelag: e.target.value
    })
  }
  
  render() {
    return (
      <>
        <Selectbox doChange={this.doChange} />
        <Clock time={this.state.nowTime} />
      </>
    )
  };
}

export default App

① componentDidMount()

コンポーネントがマウントされた(ツリーに挿入された)直後に呼び出されます。DOM ノードを必要とする初期化はここで行われるべきです。

イベントハンドラで直接ステートにセットすると時刻を変えるたびに、setInterval()が呼び出されてしまうので、今回はcomponentDidMount()を使いました。
[React公式ドキュメント]
https://ja.reactjs.org/docs/react-component.html#componentdidmount

② バインド

初学者は引っかかりがちだと思います。(私は引っかかりました)バインドするか、アロー関数で書くかしないとうまく動きません。

Selectbox.js

import React, { Component } from 'react'

class Selectbox extends Component {
  render() {
    const cities = [
      {timelag:'0',   name:'東京'},
      {timelag:'-1',  name:'シンガポール'},
      {timelag:'-7',  name:'ヘルシンキ'},  // ただのフィンランド好きなだけ
      {timelag:'-8',  name:'パリ'},
      {timelag:'-13', name:'ニューヨーク'}
    ]
    return (
      <select name='city' onChange={this.props.doChange}>
        {cities.map((city) => {
          return <option key={city.timelag} value={city.timelag}>{city.name}</option>
        })}
      </select>
    )
  }
}

export default Selectbox

ここで、国と時差を入れることができます。

Clock.js
import React, { Component } from 'react'

class Clock extends Component {
  render() {
    return ( 
      <h2>{this.props.time}</h2>
    )
  }
}

export default Clock

Clockは描画するだけです。Reactにおいて、コンポーネントに分けることはとても重要らしいので。

まとめ

だらだらコードを書くだけになってしまいましたが、Reactを始めたばかりの方の参考教材になれば大満足です。ところどころに、React(もしくはES6)に必要なスキルを散りばめているので、わからない部分は調べてみてください。

ps

material-uiでかっこよくしていきたいです。
https://material-ui.com

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?