Open In App

Build a Anagram Checker App Using ReactJS

Last Updated : 25 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will create an Anagram Checker App using React. Anagrams are­ words or phrases that can be formed by re­arranging the letters of anothe­r word or phrase, using each lette­r exactly once. This app will enable users to enter two words or phrase­s and determine if they are anagrams of each other. Moreover, it provides the option for users to switch between che­cking anagram possibilities for words or numbers.

Preview Image:

Build-a-Anagram-Checker-App-Using-React

Approach:

In the Anagram Che­cker App, users have the option to input two words or numbers and switch between word and number-checking modes using a toggle­ checkbox. The “Check” button re­mains inactive until both input fields are fille­d. Once the user clicks on the­ “Check” button, the app examine­s whether the inputs form anagrams. In case­ they do, a success message­ with a green background is displayed. Howe­ver, if the inputs are not anagrams or if the­ input fields are empty, an message with a red background appe­ars. 

Steps to Create a React Application:

  • Create a react application by using this command
npx create-react-app anagramApp
  • After creating your project folder, i.e. anagramApp, use the following command to navigate to it:
cd anagramApp

Project Structure:

The package.json file will look like:

{
"name": "anagram-checker-app",
"version": "0.0.0",
"description": "Anagram Checker App using React",
"main": "index.js",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"dependencies": {
"react": "18.2.0",
"react-dom": "18.2.0",
"react-scripts": "4.0.3"
},
"devDependencies": {},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

Example : Write the below code in App.js file and style.css in the src directory

Javascript




import React, { useState } from 'react';
import './style.css'; // Import the external CSS file
  
function App() {
    const [word1, setWord1] = useState('');
    const [word2, setWord2] = useState('');
    const [result, setResult] = useState('');
    const [isAnagram, setIsAnagram] = useState(false);
    const [checkNumbers, setCheckNumbers] = useState(false);
  
    const handleWord1Change = (e) => {
        setWord1(e.target.value.toLowerCase());
    };
  
    const handleWord2Change = (e) => {
        setWord2(e.target.value.toLowerCase());
    };
  
    const handleToggleChange = () => {
        setCheckNumbers(!checkNumbers);
    };
  
    const checkAnagram = () => {
      
        // Remove spaces and punctuation from both words
        const cleanedWord1 = checkNumbers
            ? word1.replace(/[^0-9]/g, '')
            : word1.replace(/[^\w]/g, '');
  
        const cleanedWord2 = checkNumbers
            ? word2.replace(/[^0-9]/g, '')
            : word2.replace(/[^\w]/g, '');
  
        // Check if the lengths are the same
        if (cleanedWord1.length !== cleanedWord2.length) {
            setResult('Not an anagram');
            setIsAnagram(false);
            return;
        }
  
        // Count character occurrences in the first word
        const charCount1 = {};
        for (const char of cleanedWord1) {
            charCount1[char] = (charCount1[char] || 0) + 1;
        }
  
        // Count character occurrences in the second word
        const charCount2 = {};
        for (const char of cleanedWord2) {
            charCount2[char] = (charCount2[char] || 0) + 1;
        }
  
        // Compare character counts
        for (const char in charCount1) {
            if (charCount1[char] !== charCount2[char]) {
                setResult('Not an anagram');
                setIsAnagram(false);
                return;
            }
        }
  
        // If all character counts are the same, it's an anagram
        setResult("It's an anagram!");
        setIsAnagram(true);
    };
  
    return (
        <div className="container">
            <h1 className="heading">Anagram Checker</h1>
            <p className="desc">
                Enter two 
                {checkNumbers ? 'numbers' : 'words'
                to check if they are
                anagrams:
            </p>
            <div className="inputs">
                <input
                    type="text"
                    placeholder=
                        {`Enter ${checkNumbers ? 'number' : 'word'} 1`}
                    value={word1}
                    onChange={handleWord1Change}
                    className="input"
                />
                <input
                    type="text"
                    placeholder=
                        {`Enter ${checkNumbers ? 'number' : 'word'} 2`}
                    value={word2}
                    onChange={handleWord2Change}
                    className="input"
                />
            </div>
            <label className="toggleLabel">
                Check for numbers:
                <input
                    type="checkbox"
                    checked={checkNumbers}
                    onChange={handleToggleChange}
                    className="toggleCheckbox"
                />
            </label>
            <button id="btn" onClick={checkAnagram} 
                    className="button">
                Check
            </button>
            <p id="result" 
               className={isAnagram ? 'result success' : 'result error'}>
                {result}
            </p>
        </div>
    );
}
export default App;


CSS




/* style.css */
.container {
    width: 90%;
    max-width: 31.25em;
    background-color: #ffffff;
    padding: 2em;
    position: absolute;
    transform: translate(-50%, -50%);
    left: 50%;
    top: 50%;
    border-radius: 1em;
    font-family: 'Poppins', sans-serif;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
  
.heading {
    font-size: 1.5em;
    margin-bottom: 1em;
    color: #0083e8;
    text-align: center;
}
  
.desc {
    font-size: 1.2em;
    margin: 1em 0 2em 0;
    color: #333;
}
  
.inputs {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 2em;
}
  
.input {
    width: 100%;
    border: 1px solid #ccc;
    padding: 0.5em;
    outline: none;
    border-radius: 0.3em;
    font-size: 1em;
}
  
.button {
    display: block;
    margin: 0 auto;
    background-color: #0083e8;
    color: #ffffff;
    border: none;
    outline: none;
    padding: 0.7em 2em;
    border-radius: 0.5em;
    font-size: 1em;
    cursor: pointer;
}
  
.toggleLabel {
    display: flex;
    align-items: center;
    margin-bottom: 1em;
    font-size: 1.2em;
    color: #333;
}
  
.toggleCheckbox {
    margin: 10px;
}
  
.result {
    text-align: center;
    margin-top: 1em;
    font-size: 1.2em;
    font-weight: bold;
}
  
.success {
    color: #078307;
    background-color: #d0ffd0;
}
  
.error {
    color: #a00606;
    background-color: #ffc4b0;
}


Steps to run the Application:

  • Type the following command in the terminal:
npm start
  • Type the following URL in the browser:
 http://localhost:3000/

Output:Build-a-Anagram-Checker-App-Using-React



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads