[Introduction to React] Learn by making a rock-paper-scissors game! Implementation guide for beginners

programming

For beginners who want to learn React but don't know what to make.
The rock-paper-scissors game isReact's basics: useState, event handling, and conditional branchingIt's a perfect teaching material that has it all.
In this article, we will show you how to make it easily.How to implement a React rock-paper-scissors gameWe will explain this in detail with code.

How to make a Rock-Paper-Scissors game with React

Conclusion: Rock-Paper-Scissors is a treasure trove of React basics

ReactState management, event processing, and conditional branchingThe biggest advantage is that you can learn in a fun and intuitive way.
This is ideal for those who want to get a grasp of the overall picture of React.

Environment construction and preparation

What you need

  • Node.js (https://nodejs.org/ja)
  • npm (included in Node.js)
  • create-react-app

In the terminal run:

1

Basic design required for games

Features to be implemented

  • User-selected "rock, scissors, paper" buttons
  • Random computer moves
  • Judging the winner
  • Score display (win/lose/tie)

Main code implementation steps

Full code for App.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
;
  , , ];
  );
  );
  );
  
  
     ;
     (
       ) ||
       ) ||
       )
    ) {
       ;
    }
     ;
  };
  
    
    
    
    
    
    
       ? 1 : 0),
       ? 1 : 0),
       ? 1 : 0),
    }));
  };
   (
     }}>
      
      
        
          
            
          
        ))}
      
      
      
      
      
    
  );
}

Common stumbling blocks and how to deal with them

Computer hands unchanged?

Even if you generate it with Math.random, it will not be updated if the rendering is not appropriate.useState and useEffectThis can be resolved through collaboration.

The logic of winning and losing is hard to understand

All three conditions must be covered.Write if statements carefullyIt's the shortcut.

Useful links and resources for your study

  • React official tutorial: https://ja.reactjs.org/tutorial/tutorial.html
  • GIGA School Initiative (Ministry of Education, Culture, Sports, Science and Technology): https://www.mext.go.jp/a_menu/other/index_00001.htm
  • Related articles:

Completed code summary

Just paste the code introduced in this article into App.js,A rock-paper-scissors app that works instantlyis completed.
For beginners, after copying and pasting the codeCheck the meaning of each process one by oneWe recommend that you do so.

Summary: The best introductory app for fun learning

React Rock Paper Scissors GameThe best introductory material that combines fun and learningis.
Based on this implementation, feel free to expand it to the next step, such as saving scores or adding animations.

Copied title and URL