DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Unleashing the Power of GPT: A Comprehensive Guide To Implementing OpenAI’s GPT in ReactJS
  • How We Reduced LCP by 75% in a Production React App
  • Shipping GenAI Into an Existing App: How to Integrate AI Features Without Rewriting Your Stack
  • AWS Agentic AI for App Portfolio Modernization

Trending

  • The Cost of Knowing: When Observability Becomes the Outage
  • The 7 Pillars of Meeting Design: Transforming Expensive Conversations into Decision Assets
  • AI Agents Expose a Design Gap in Microservices Resilience Architecture
  • Genkit Middleware: Intercept, Extend, and Harden your Gen AI Pipelines
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Building an AI-Powered Text Analysis App With React: A Step-by-Step Guide

Building an AI-Powered Text Analysis App With React: A Step-by-Step Guide

Build an AI-powered text analysis app using React, Vite, and OpenAI GPT-3.5, featuring sentiment analysis, topic extraction, summarization, and language detection.

By 
Raju Dandigam user avatar
Raju Dandigam
·
Jun. 25, 25 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
3.1K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we will walk through the step-by-step implementation of an AI Text Analysis App using React, Vite, and OpenAI's GPT-3.5. This app will allow users to input text and analyze it for sentiment, topics, summary, and language detection. By the end of this guide, even beginners will be able to build and understand this application. We will also explain each feature in detail and provide examples to ensure clarity.

Introduction

The AI Text Analysis App is a powerful tool that leverages OpenAI's GPT-3.5 to analyze text. It provides insights into the emotional tone of the text (sentiment), identifies the main topics, generates a concise summary, and detects the language of the input text. This app is built using React for the front end, Vite for fast development, and Tailwind CSS for styling.

Step 1: Setting Up the Project

Create a New React App With Vite

We will use Vite to create a new React app because it is fast and modern.

  1. Launch your terminal and execute the command below. During the project initialization, select React as the framework and configure it to use TypeScript for type-safe development.
    npm create vite@latest ai-text-analysis-app
  2. Navigate to the project directory:
    cd ai-text-analysis-app
  3. Install the dependencies:
    npm install

Install Required Dependencies

Let’s add some extra packages required to enhance the app’s functionality:

  1. Tailwind CSS: For styling the app.
  2. Lucide React: For icons.
  3. OpenAI: To interact with the OpenAI API.

Execute the command below to install the required packages for this project:
npm install tailwindcss postcss autoprefixer lucide-react openai

Set Up Tailwind CSS

1. Initialize Tailwind CSS:
npx tailwindcss init -p

2. Open the tailwind.config.js file and configure it to include all necessary files:

JavaScript
 
export default {
  content: [
      "./index.html",
      "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
  extend: {},
  },
  plugins: [],
}


3. Navigate to the src/index.css file and overwrite its contents with the code below:

JavaScript
 
@tailwind base;
@tailwind components;
@tailwind utilities;


Step 2: Create the OpenAI Service

Set Up OpenAI API Key

  1. Create a .env file in the root of your project:
    VITE_OPENAI_API_KEY=your_openai_api_key_here
  2. Replace your_openai_api_key_here with your actual OpenAI API key.
  3. Add the .env file to your .gitignore to avoid committing sensitive information:
    .env

Create the OpenAI Service

Create a new folder src/services and add a file named openai.ts:

JavaScript
 
import OpenAI from 'openai';
import { AnalysisResult, AIError } from '../types/ai';

const openai = new OpenAI({
  apiKey: import.meta.env.VITE_OPENAI_API_KEY,
  dangerouslyAllowBrowser: true
});

export async function analyzeText(text: string): Promise<AnalysisResult> {
  try {
    const response = await openai.chat.completions.create({
      model: "gpt-3.5-turbo",
      messages: [{
      role: "system",
      content: "Analyze the following text and provide sentiment, main topics, a brief summary, and detected language. Return as JSON."
      }, {
      role: "user",
      content: text
      }],
      response_format: { type: "json_object" }
  });

  return JSON.parse(response.choices[0].message?.content || '{}');
  } catch (error) {
    throw {
      message: 'Failed to analyze text',
      code: error instanceof Error ? error.message : 'UNKNOWN_ERROR'
    } as AIError;
 }
}


This service sends the user's text to OpenAI's GPT-3.5 model and returns the analysis result.

Step 3: Define Types

Create Type Definitions

Create a new folder src/types and add a file named ai.ts:

JavaScript
 
export interface AnalysisResult {
  sentiment: string;
  topics: string[];
  summary: string;
  language: string;
}

export interface AIError {
  message: string;
  code?: string;
}

These types define the structure of the analysis result and error objects.


Step 4: Build the Components

TextInput Component

This component allows users to input text and submit it for analysis.

Within your project structure, generate a src/components directory and populate it with a TextInput.tsx file to house the component logic.

JavaScript
 
import React from 'react';
import { Send } from 'lucide-react';

interface TextInputProps {
  value: string;
  onChange: (value: string) => void;
  onSubmit: () => void;
  isLoading: boolean;
}

export function TextInput({ value, onChange, onSubmit, isLoading }: TextInputProps) {
  return (
    <div className="relative">
      <textarea
        className="w-full h-32 p-4 border rounded-lg resize-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
        placeholder="Enter text to analyze..."
        value={value}
        onChange={(e) => onChange(e.target.value)}
      />
      <button
        onClick={onSubmit}
        disabled={isLoading || !value.trim()}
        className="absolute bottom-4 right-4 bg-indigo-600 text-white p-2 rounded-full hover:bg-indigo-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
        >
        <Send className="w-5 h-5" />
      </button>
    </div>
  );
}


AnalysisResult Component

This component displays the analysis result.

Create a file named AnalysisResult.tsx in the src/components folder:

JavaScript
 
import React from 'react';
import { Brain, List, MessageSquare, Globe } from 'lucide-react';
import { AnalysisResult } from '../types/ai';

interface AnalysisResultProps {
  result: AnalysisResult;
}

export function AnalysisResultView({ result }: AnalysisResultProps) {
  return (
    <div className="space-y-6">
      <div className="flex items-start space-x-3">
        <Brain className="w-6 h-6 text-indigo-600" />
        <div>
          <h3 className="font-semibold">Sentiment</h3>
          <p className="text-gray-700">{result.sentiment}</p>
        </div>
      </div>

      <div className="flex items-start space-x-3">
        <List className="w-6 h-6 text-indigo-600" />
        <div>
          <h3 className="font-semibold">Topics</h3>
          <ul className="list-disc list-inside text-gray-700">
          {result.topics.map((topic, index) => (
            <li key={index}>{topic}</li>
          ))}
          </ul>
        </div>
      </div>

      <div className="flex items-start space-x-3">
        <MessageSquare className="w-6 h-6 text-indigo-600" />
        <div>
          <h3 className="font-semibold">Summary</h3>
          <p className="text-gray-700">{result.summary}</p>
        </div>
      </div>

      <div className="flex items-start space-x-3">
        <Globe className="w-6 h-6 text-indigo-600" />
        <div>
          <h3 className="font-semibold">Language</h3>
          <p className="text-gray-700">{result.language}</p>
        </div>
      </div>
    </div>
  );
}


ErrorMessage Component

This component displays errors.

Create an ErrorMessage.tsx file inside the src/components directory to encapsulate your error display logic.

JavaScript
 
import React from 'react';
import { AlertCircle } from 'lucide-react';
import { AIError } from '../types/ai';

interface ErrorMessageProps {
  error: AIError;
  onDismiss: () => void;
}

export function ErrorMessage({ error, onDismiss }: ErrorMessageProps) {
  return (
    <div className="bg-red-50 border-l-4 border-red-400 p-4">
      <div className="flex items-start">
        <AlertCircle className="w-5 h-5 text-red-400" />
        <div className="ml-3 flex-1">
          <p className="text-sm text-red-700">{error.message}</p>
          {error.code && (
            <p className="mt-1 text-xs text-red-500"> Error code: {error.code} </p>
          )}
        </div>
        <button
          onClick={onDismiss}
          className="ml-auto text-red-400 hover:text-red-500"
        >
          ×
        </button>
      </div>
    </div>
  );
}


Step 5: Build the Main App Component

JavaScript
 
import React, { useState } from 'react';
import { TextInput } from './components/TextInput';
import { AnalysisResultView } from './components/AnalysisResult';
import { ErrorMessage } from './components/ErrorMessage';
import { analyzeText } from './services/openai';
import type { AnalysisResult, AIError } from './types/ai';

function App() {
  const [text, setText] = useState('');
  const [result, setResult] = useState<AnalysisResult | null>(null);
  const [error, setError] = useState<AIError | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  const handleAnalyze = async () => {
    setIsLoading(true);
    setError(null);
    try {
      const analysis = await analyzeText(text);
      setResult(analysis);
    } catch (err) {
      setError(err as AIError);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-3xl mx-auto px-4">
        <h1 className="text-3xl font-bold text-center mb-8">AI Text Analysis</h1>
        
        <div className="bg-white rounded-lg shadow-sm p-6 space-y-6">
          <TextInput
            value={text}
            onChange={setText}
            onSubmit={handleAnalyze}
            isLoading={isLoading}
          />

          {error && (
            <ErrorMessage
              error={error}
              onDismiss={() => setError(null)}
            />
          )}

          {isLoading && (
            <div className="text-center text-gray-600">
              Analyzing text...
            </div>
          )}

          {result && !isLoading && (
            <AnalysisResultView result={result} />
          )}
        </div>
      </div>
    </div>
  );
}

export default App;


Step 6: Run the App

  1. Spin up the development server by executing npm run dev in your terminal.
  2. Access the application through your browser at http://localhost:5173.
  3. Interact with the UI: Type into the input field and hit the Send button to trigger the analysis and view the output results.

FAQ Section

What is Sentiment Analysis?

Sentiment analysis is a Natural Language Processing (NLP) technique that identifies the emotional tone within a body of text. It classifies the input as positive, negative, or neutral, helping systems interpret subjective content.

How does Topic Extraction work?

Topic Extraction identifies the main subjects and themes discussed in the text. It helps in categorizing content and understanding the key points of a document.

What is Text Summarization?

Text Summarization creates concise summaries of longer texts. It is useful for quickly understanding the main points of lengthy documents, articles, or reports.

How is Language Detection useful?

Language Detection identifies the language of the input text. It is useful for multilingual applications where the language of the text needs to be determined before further processing.

Can I use this app for commercial purposes?

Yes, the AI Text Analysis App is licensed under the MIT License, which allows you to use it for both personal and commercial purposes.

How do I get an OpenAI API key?

You can get an OpenAI API key by signing up on the OpenAI website and creating an API key in your account settings.

Is this app secure?

Yes, the app is designed with security in mind. It uses environment variables to store sensitive data like the OpenAI API key and implements error handling to manage API call failures.

Can I customize the app?

Absolutely! The app is built with React and TypeScript, making it easy to customize and extend according to your needs.

By following this guide, you should now have a solid understanding of how to build and use the AI Text Analysis App. Happy coding!

Conclusion

You have successfully built an AI Text Analysis App using React, Vite, and OpenAI's GPT-3.5. This app analyzes text for sentiment, topics, summary, and language detection. You can now extend this app by adding more features or integrating it into your projects.

AI app React (JavaScript library)

Opinions expressed by DZone contributors are their own.

Related

  • Unleashing the Power of GPT: A Comprehensive Guide To Implementing OpenAI’s GPT in ReactJS
  • How We Reduced LCP by 75% in a Production React App
  • Shipping GenAI Into an Existing App: How to Integrate AI Features Without Rewriting Your Stack
  • AWS Agentic AI for App Portfolio Modernization

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook