LoginSignup
4
2

More than 3 years have passed since last update.

ReactをRedux+TypeScriptで始めてみる

Last updated at Posted at 2019-02-13

はじめに

普段はAngularを使っているので、他のフレームワークを触ってみようと思った今日このごろ。
Vueは超絶軽く触ったことがあるので今回はReact。
JSXがパッと見とっつきにくかったので後回しにしてたけど、ちゃんと向き合うことにする。

TL;DR.

今回作ったサンプルコード

インストール

手作業でファイルを作ってもいいけど、Facebook作成のcreate-react-appがあるのでそれを使う。

$ npm install -g create-react-app
# TSを使いたいからオプション指定
$ create-react-app react-sample --typescript

サンプルプログラムを作る

いつも?通りToDoリストを作ることにする。
今回Reactのサンプルなので、せっかくだからReduxも導入することにする。
インストールは下記の通りでOK。

# 必要なライブラリのインストール
$ npm install -save redux react-redux

# 実装時楽したいので型定義もインストール
$ npm install --save-dev @types/react @types/react-redux

サンプルの実装はReduxの公式サイトのサンプルプログラムを参考にしてTSへリファクタしていくことにする。
今回のリファクタリングの方針は下記の通りにした。
ちなみにこれがベストかどうかはわからないので、あくまで今回の方針とする。

  • DOM作ってるところは.tsxにする
  • component周りはclassにする
  • propTypesの代わりにTSのinterfaceを使う

サンプルコード

全量は流石に多いのでGitに上げた。
ActionとかReducerは型つけたぐらいなので、Componentとinterfasceをサンプルとして載せとく。

Component

import React, { Component } from 'react';
import { ITodoProps } from '../commons/interfaces';

export default class Todo extends Component<ITodoProps, {}> {

  render() {
    return (
      <li
        onClick={this.props.onClick}
        style={{
          textDecoration: this.props.completed ? 'line-through' : 'none'
        }}
      >
        {this.props.text}
      </li>
    );
  }
}

interface

export interface ITodoProps {
    completed: boolean;
    id: number;
    onClick: any;
    text: string
}

export interface ITodoListProps {
    todos?: Array<ITodoProps>;
    toggleTodo: any;
}

export interface ILinkProps {
    active: boolean;
    children: string;
    onClick: any;
    filter: string
}

export interface IState {
    todos: Array<any>;
    visibilityFilter: string;
}

まとめ

今回は簡単にReact + Reduxのチュートリアルをやってみた。
JSX(TSX)の書き方はとっつきにくいかなって思ってたけど、意外とそうでもなかった。
Reactが学習コスト低めって言われている理由がちょっとわかった気がする。
そのうちオリジナルの何かを作ろうと思った。
それでは今回はこの辺で。

参考サイト

4
2
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
4
2