A simple react 17 game snippet

A simple game code using React 17. Let’s create a basic guessing game where the player needs to guess a random number between 1 and 100. Here’s how you can implement it:

  1. Set up your React project: Make sure you have Node.js and npm installed. Create a new React app by running these commands in your terminal:
npx create-react-app guessing-game
cd guessing-game
  1. Modify src/App.js with the following code:
import React, { useState } from 'react';
import './App.css';

function App() {
  const [targetNumber, setTargetNumber] = useState(generateRandomNumber());
  const [guess, setGuess] = useState('');
  const [message, setMessage] = useState('');

  function generateRandomNumber() {
    return Math.floor(Math.random() * 100) + 1;

  function handleGuess(event) {
    const guessedNumber = parseInt(guess, 10);

    if (isNaN(guessedNumber)) {
      setMessage('Please enter a valid number.');
    } else if (guessedNumber === targetNumber) {
      setMessage('Congratulations! You guessed the correct number.');
    } else if (guessedNumber < targetNumber) {
      setMessage('Try a higher number.');
    } else {
      setMessage('Try a lower number.');

  return (
    <div className="App">
      <h1>Guessing Game</h1>
      <p>Guess a number between 1 and 100.</p>
      <form onSubmit={handleGuess}>
          onChange={(e) => setGuess(e.target.value)}
        <button type="submit">Submit Guess</button>

export default App;
  1. Run the app: In your terminal, go to the project directory and run:
npm start

This will start the development server, and you can view the guessing game in your web browser at http://localhost:3000.

Leave a Reply

Your email address will not be published. Required fields are marked *.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>