LoginSignup
1
0

More than 3 years have passed since last update.

React初心者だけどUbuntu18.04上でcreate-react-appとReact Hooksを使ってサクッとカウンタを作る

Posted at

初投稿です。私もReactの勉強を最近始めたばかりなので備忘録的に。
色々すっ飛ばしてます。

まずはUbuntuのバージョン確認

Ubuntu上で作ります。

% cat /etc/os-release 
NAME="Ubuntu"
VERSION="18.04.3 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.3 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic

yarnをインストール

yarn公式に従ってください
https://yarnpkg.com/lang/en/docs/install/#debian-stable

$ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -  
$ echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
$ sudo apt update && sudo apt install yarn

create-react-appをインストール

これもyarn公式に従ってください
https://yarnpkg.com/lang/en/docs/cli/create/

$ yarn global add create-react-app

こんな感じのメッセージが出ればOK(多分)。

success Installed "create-react-app@3.2.0" with binaries:
      - create-react-app
Done in 9.51s.

$ yarn --version
1.17.3

create-react-appコマンドを叩く。

下のコマンドでカレントディレクトリにmy-react-appというディレクトリが作られる。
my-react-appの直下にReactでアプリを作るのに必要な諸々のファイルが自動的に作られる。

$ create-react-app my-react-app

成功するとこんなメッセージが出る。

Success! Created my-react-app at /home/koralle/learn/my-react-app
Inside that directory, you can run several commands:

  yarn start
    Starts the development server.

  yarn build
    Bundles the app into static files for production.

  yarn test
    Starts the test runner.

  yarn eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd my-react-app
  yarn start

Happy hacking!

$ create-react-app --version
3.1.2

試しにアプリを起動してみる。

$ cd my-react-app
$ yarn start

ちょっと待つとこんなメッセージになる。

Compiled successfully!

You can now view my-react-app in the browser.

  Local:            http://localhost:3000/
  On Your Network:  http://10.0.2.15:3000/

Note that the development build is not optimized.
To create a production build, use yarn build.

言われたとおりにブラウザで http://localhost:3000/ にアクセスします。
というか人によっては自動的にブラウザでページが立ち上がります。

こんな感じ。
無題.png

次からが本題。

カウンタを作るための準備

まずはmy-react-app直下のディレクトリ構成を確認
今回触るのは./public/index.html./src/App.jsだけです。

$ cd my-react-app
$ ls
README.md  node_modules  package.json  public  src  yarn.lock

$ tree ./public
./public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt

0 directories, 6 files

$ tree ./src
./src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
└── serviceWorker.js

0 directories, 7 files

先にindex.htmlを開く。今回はできる限り余計なものを全部消します。邪魔なので。
私はこれだけ残しました。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

次は./src/App.jsを編集。
function App()全体がいわゆるAppコンポーネントっていうやつですが、
一回こいつを全部消します。
そしてAppコンポーネントをアロー関数式で書き直す。アロー関数式、おしゃれな感じが好きです。

import React from 'react';
import logo from './logo.svg';
import './App.css';

const App = () => {

} 

export default App;

一回途中経過を見たいので先にカウンタのボタンを作ります。
Appコンポーネント以外はいったん省略します。


const App = ()=> {

  return(
    <div>
      <button> + </button>
      <button> - </button>
    </div>
  );
}

こんな感じ。小さいけど確かに+ボタンと-ボタンが表示されてます。
無題1.png

次にカウンタを作ります。そのために必要なのはあと最低限以下の二つです。

  • カウンタの値を保持する変数 (*1)
  • カウンタの値を増減させる関数 (*2)

これらを実装するために、今回はReact HooksというReact公式APIの中のuseState()という関数を利用します。
詳しくは公式ドキュメントを見てください。

フック早わかり – React
https://ja.reactjs.org/docs/hooks-overview.html

書式は今回の場合こんな感じ。
countが上記の(*1)で、setCountは(*2)とイコールではないですが、(*2)の実装に必要になります。
useState(0)の0はcountの初期値です。

const [count, setCount] = useState(0);

これを使って./src/App.jsにカウンタの動作を書きますが、1行目もちょっと編集します。

import React, {useState} from 'react';
import logo from './logo.svg';
import './App.css';

const App = () => {
  // (*1), (*2)の実装に必要
  const [count, setCount] = useState(0);

  const increment = () => setCount(count+1); // カウンタの値を増やす
  const decrement = () => setCount(count-1); // カウンタの値を減らす

  // index.htmlの<div id="root"></div>の中に表示
  return(
    <div>
      <p> {count} </p>
      <button onClick={increment}> + </button>
      <button onClick={decrement}> - </button>
    </div>
  );
} 

export default App;

これで完成

カウンタの値を増やす
増やす.png

カウンタの値を減らす
減らす.png

1
0
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
1
0