Skip to content

Instantly share code, notes, and snippets.

@ekaone
Created October 18, 2024 02:16
Show Gist options
  • Select an option

  • Save ekaone/d6e7cb687963cfbadb7b251332ae6862 to your computer and use it in GitHub Desktop.

Select an option

Save ekaone/d6e7cb687963cfbadb7b251332ae6862 to your computer and use it in GitHub Desktop.
Simple UI Sentiment analysis input field
'use client'
import { useState } from 'react'
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { ThumbsUp, ThumbsDown, Loader2 } from "lucide-react"
export default function SentimentAnalysis() {
const [text, setText] = useState('')
const [sentiment, setSentiment] = useState<'positive' | 'negative' | 'neutral' | null>(null)
const [loading, setLoading] = useState(false)
const analyzeSentiment = async () => {
setLoading(true)
try {
// Replace this with your actual sentiment analysis API endpoint
const response = await fetch('/api/analyze-sentiment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text })
})
const data = await response.json()
setSentiment(data.sentiment)
} catch (error) {
console.error('Error analyzing sentiment:', error)
setSentiment(null)
} finally {
setLoading(false)
}
}
const getSentimentIcon = () => {
switch (sentiment) {
case 'positive':
return <ThumbsUp className="h-6 w-6 text-green-500" />
case 'negative':
return <ThumbsDown className="h-6 w-6 text-red-500" />
default:
return null
}
}
const getSentimentColor = () => {
switch (sentiment) {
case 'positive':
return 'text-green-500'
case 'negative':
return 'text-red-500'
case 'neutral':
return 'text-yellow-500'
default:
return ''
}
}
return (
<Card className="w-full max-w-md mx-auto">
<CardHeader>
<CardTitle>Sentiment Analysis</CardTitle>
<CardDescription>Enter text to analyze its sentiment</CardDescription>
</CardHeader>
<CardContent>
<Textarea
placeholder="Enter text here..."
value={text}
onChange={(e) => setText(e.target.value)}
className="mb-4"
rows={4}
/>
<Button onClick={analyzeSentiment} disabled={!text || loading} className="w-full mb-4">
{loading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Analyzing...
</>
) : (
'Analyze Sentiment'
)}
</Button>
{sentiment && (
<div className="flex items-center justify-center space-x-2">
{getSentimentIcon()}
<span className={`text-lg font-semibold ${getSentimentColor()}`}>
{sentiment.charAt(0).toUpperCase() + sentiment.slice(1)}
</span>
</div>
)}
</CardContent>
</Card>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment