1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React特訓02: ランダムで✊✌️✋を表示してジャンケンしよう

Posted at

はじめに

私がReactを学習するにあたって、AIに頼らずコードを描けるようになるために解いた問題を、アウトプットとして残していきます。

この問題はAIを使用して作成したもので、以下の流れで学習を進めたものになります。

1. AIに問題を作らせる
2. 調べながらやってみる
3. 困ったらAIに質問する
4. AIにレビューしてもらう

問題

クリックするとランダムで✊✌️✋が表示されるボタンを作成しよう

要件

  • 初期状態は結果は表示しない
  • ボタンをクリックするたびに絵文字がランダムに1つずつ表示

ポイント

  • useStateによる状態管理
  • ランダム関数を使用した配列要素の取得
  • Reactでの基本的なイベント処理

完成系

  • 初期状態
    スクリーンショット 2025-05-04 18.19.47.png
  • ボタンをクリックするたびランダムに表示が変わる
    スクリーンショット 2025-05-04 18.20.12.png
    スクリーンショット 2025-05-04 18.20.32.png
    スクリーンショット 2025-05-04 18.20.47.png

解答

import React, { useState } from 'react';

function HandRandomizer() {
  const hands = ['', '✌️', ''];
  const [handSelected, setHandSelected] = useState('');
  const handleClick = () => {
    const randomIndex = Math.floor(Math.random() * hands.length);
    setHandSelected(hands[randomIndex]);
  }

  return (
    <div className="text-center">
      <button onClick={handleClick} className="bg-blue-500 rounded-lg text-white p-2 my-4">最初はグー!ジャンケンっ</button>
      <p className="text-4xl">{handSelected}</p>
    </div>
  );
}

export default HandRandomizer;

解説

記述の手順
1. 関数コンポーネントを作成
2. 絵文字の選択肢を配列で用意
3. 選ばれた絵文字を'state'で管理
4. UIを作成
5. ボタンにonClickイベントを設定
6. ランダム表示用のクリック関数を作成(コールバック関数)

以下から順に進めます。


1. 関数コンポーネントを作成

function HandRandomizer() {

2. 絵文字の選択肢を配列で用意

✊✌️✋を文字列として配列の要素にします。

const hands = ['', '✌️', ''];

3. 選ばれた絵文字を'state'で管理

初期値は空の文字列。

 const [handSelected, setHandSelected] = useState('');

4. UIを作成

TailWindを使用してお好みのスタイルに調整

  return (
    <div className="text-center">
      <button className="bg-blue-500 rounded-lg text-white p-2 my-4">最初はグー!ジャンケンっ</button>
      <p className="text-4xl">{/*ここに結果を表示*/}</p>
    </div>
  );

5. ボタンにonClickイベントを設定

  <button onClick={handleClick} className="bg-blue-500…">

6. ランダム表示用のクリック関数を作成(コールバック関数)

Mathオブジェクトのメソッドを使用して、配列の中身をランダムで取得する。

構文 説明
Math.random() 0以上1未満の小数を返す(例:0.215、0.878など)
* hands.length hands配列の要素数を掛けることで、0〜(length未満)の数値に
Math.floor() 小数点を切り捨てて整数にする(例:2.999 → 2)
  const handleClick = () => {
    const randomIndex = Math.floor(Math.random() * hands.length);
    setHandSelected(hands[randomIndex]);
  }
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?