<< Click to Display Table of Contents >> Navigation: Analogues > React > Guess Web Application |
Here we will build a number guessing game using React. The application generates a random number between 1 and 100, and the user tries to guess it. After each attempt, the app responds with feedback like “too low” or “too high” until the user finds the correct answer.
Before diving into the code, let’s walk through how to create and prepare a React project that will host this application.
Editing App.jsx
The App.jsx file manages the application’s state, handles input, and contains the core logic. Open it in any text editor and replace its content with the following code:
// Import necessary React hooks:
// useState for state management
// useEffect for side effects
// useRef for DOM element references
import React, { useState, useEffect, useRef } from 'react';
const App = () => {
// State for storing user's current input
const [guess, setGuess] = useState('');
// State for messages to user (hints, errors)
const [message, setMessage] = useState('');
// Attempt counter
const [count, setCount] = useState(0);
// The random target number between 1-100
const [magicNo, setMagicNo] = useState(Math.floor(Math.random() * 100) + 1);
// Flag to enable/disable the button
const [isButtonEnabled, setIsButtonEnabled] = useState(true);
// Reference to the input DOM element for focus control
const guessInputRef = useRef(null);
// Effect that runs once on component mount
useEffect(() => {
// Focus the input field on load
guessInputRef.current.focus();
// Parse URL query parameters
const params = new URLSearchParams(window.location.search);
// Get MagicNo parameter from URL
const magicNoParam = params.get('MagicNo');
// If valid number provided in URL, use it as target
if (magicNoParam && !isNaN(parseInt(magicNoParam))) {
setMagicNo(parseInt(magicNoParam));
}
}, []); // Empty dependency array means effect runs only once on mount
// Guess button click handler
const handleGuess = (e) => {
// If Shift key pressed - reveal the magic number
if (e.shiftKey) {
alert(`The magic number is: ${magicNo}`);
return;
}
// Clear previous message
setMessage('');
// Convert input to number
const guessValue = parseInt(guess);
// Validate user input
if (isNaN(guessValue)) {
setMessage(`${guess} is not a valid number.`);
} else if (guessValue < 1 || guessValue > 100) {
setMessage(`${guessValue} is not in the range of 1 to 100.`);
} else {
// Increment attempt counter
setCount(count + 1);
// Compare with target number
if (guessValue < magicNo) {
setMessage(`${guessValue} is too low.`);
} else if (guessValue > magicNo) {
setMessage(`${guessValue} is too high.`);
} else if (guessValue === magicNo) {
// Win condition - show alert and disable controls
alert('Congratulations! You guessed the magic number.');
setIsButtonEnabled(false);
}
}
// Clear input and refocus
setGuess('');
guessInputRef.current.focus();
};
// Component render
return (
<div>
<h1>Guess the Number</h1>
<div>
{/* Number input field */}
<input
ref={guessInputRef} // Reference for focus control
type="text"
value={guess} // Controlled component
onChange={(e) => setGuess(e.target.value)} // Update state on change
placeholder="Enter a number (1-100)"
disabled={!isButtonEnabled} // Disable after win
/>
{/* Message and counter displays */}
<p>{message}</p>
<p>Guess #{count}</p>
{/* Guess submission button */}
<button
onClick={handleGuess} // Click handler
disabled={!isButtonEnabled} // Disable after win
>
Guess
</button>
</div>
</div>
);
};
// Export component for use in other files
export default App;
Editing index.jsx
This file is the entry point of the React application. It renders the main App component into the root element in the HTML.
Replace the contents of index.jsx with:
// Import core React library for component creation
import React from 'react';
// Import ReactDOM client version for DOM-specific methods
import ReactDOM from 'react-dom/client';
// Import the root App component that contains our application
import App from './App';
// Initialize the React application root container
// Locates the DOM element with id="root" from index.html
ReactDOM.createRoot(document.getElementById('root'))
// Mounts the application inside the root container
.render(
// React.StrictMode is a special component for identifying potential problems
// Includes additional checks and warnings in developer mode
<React.StrictMode>
{/* The main application component that contains all UI */}
<App />
</React.StrictMode>
);
Editing index.html
Now go back to the root of your React project and open the public folder. Inside it, you will find the file index.html.
This file task is to provide an "anchor" for React and a minimal HTML structure. All dynamic elements are generated by JavaScript through React components.
Edit index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Responsive viewport settings for mobile devices -->
<title>Guess Game</title> <!-- Page title shown in browser tab -->
</head>
<body>
<div id="root"></div> <!-- Mounting point for React application -->
<!--
Notes:
- All scripts are automatically injected by the bundler
- React will render the application inside this div
- The "root" id must match the one referenced in index.jsx
- This remains empty in development - content is dynamically generated
-->
</body>
Running the Application
Everything is now ready. To launch the application, run the following command in the terminal:
npm start
This will start a development server and open your application in the browser at http://localhost:3000.
You will see the fully functional "Guess the Number" app, with logic handled by the code you added.
Advantages of IntraWeb 17
Compared to React, creating the same “Guess the Number” game in IntraWeb 17 is often easier, faster, and involves less boilerplate code. Let’s look at why:
1.Less Code, Same Functionality
Even for a simple form with an input, a message, a counter, and a button, React requires a fair amount of boilerplate.
React (JSX + Hooks + Handlers)
<input type="text" value={guess} onChange={(e) => setGuess(e.target.value)} disabled={!isButtonEnabled} /> <p>{message}</p> <p>Guess #{count}</p> <button onClick={handleGuess} disabled={!isButtonEnabled}> Guess </button> |
IntraWeb 17 (IWML Layout)
SimpleStack Edit:GuessEdit =this.Guess Text =this.Msg Text Guess #[=this.Count] Button:GuessButton Guess |
IntraWeb lets you focus on what your app should do, not how to wire everything together. For small-to-medium interactive apps, it delivers maximum results with minimal code.
2.Simpler State Management
In React, state updates are asynchronous and require useState, setters, and often multiple hooks to coordinate state.
In IntraWeb, you work with simple class properties:
this.Msg = 'Too high!';
this.Count++;
this.Guess = NaN;
State is reactive by default, and you don’t need hooks to track or re-render — changes are instantly reflected in the UI.
3.Zero Build Tools or Compilers
React projects require:
•Node.js
•npm packages
•Bundlers (Webpack or Vite)
•JSX to JS transpilation
In contrast, IntraWeb runs natively in the browser without any additional tooling. You just:
1.Create an .iwml layout
2.Write a plain JavaScript file
3.Open it in your browser
That’s it — no build step, no dependencies.
4.Clean Separation of Layout and Logic
In React, markup and logic are mixed inside components (JSX + functions). IntraWeb keeps these concerns separate:
•Layout: .iwml file (like HTML)
•Logic: .js file with a class that extends IntraWeb.Code
This makes the code easier to read and maintain.
5.Much Smaller Project Size
Another major advantage of IntraWeb 17 is how little space it takes compared to modern JavaScript frameworks. While even the simplest React project pulls in hundreds of megabytes of dependencies, a complete IntraWeb app consists of just a few small files: the layout, the logic, and a lightweight runtime.
There’s no massive node_modules folder, no bundlers, and no toolchain overhead. The entire project is dozens of times smaller, launches instantly, and is easy to copy, share, or deploy without installation steps.
In short, IntraWeb delivers full interactivity with a fraction of the weight — clean, fast, and efficient by design.
See also