LoginSignup
0
1

More than 1 year has passed since last update.

HTML + CSS + JavaScript + React でカウンター機能を実装する

Last updated at Posted at 2021-07-24

はじめに

この記事ではReactのHooksである「useState」を使用して、カウンターアプリを作成する方法を解説します。必要な部分のみ参考にしていただけたらと思います。

ソースコード

「App.jsx」「index.js」「index.html」「styles.css」のコードはこちらになります。

App.jsx
import { useState } from "react";
import "./styles.css";

export default function App() {
  // カウント保持(初期値:0)
  const [count, setCount] = useState(0);
  // カウントアップ処理
  const countUp = () => {
    setCount(count + 1);
  };

  return (
    <div className="App">
      <h1>カウンタ</h1>
      <p> {count} </p>
      <button onClick = {countUp}></button>
    </div>
  );
}
index.js
import { StrictMode } from "react";
import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <App />
  </StrictMode>,
  rootElement
);

index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <title>React App</title>
  </head>

  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
  </body>
</html>
styles.css
.App {
  text-align: center;
}

実行結果

実行結果はこのようになります。

スクリーンショット 2021-07-24 15.27.37.png

プラスボタンをクリックすると、下記画像のように数字がカウントアップされます。

スクリーンショット 2021-07-24 15.27.42.png

以上になります。

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