How to implement sentiment analysis in React with AI
Key takeaways:
Integrating AI in React apps enhances user engagement with real-time insights.
Google Cloud Natural Language API makes sentiment analysis easy to implement in React app.
Let’s walk through a simple example of implementing sentiment analysis in a React application using the Google Cloud Natural Language API. This example will involve setting up a new React project, integrating the Google Cloud Natural Language API, and displaying the sentiment analysis results in the application.
1. Set up a new React project
First, create a new React project using the Create React App. Open your terminal and run the following commands:
npx create-react-app sentiment-analysis-reactcd sentiment-analysis-react
2. Install dependencies
Next, install the necessary dependencies for making HTTP requests and handling environment variables:
npm install axios dotenv
3. Set up Google Cloud Natural Language API
If you haven’t already, sign up for a Google Cloud account and create a new project. Enable the Cloud Natural Language API for your project and create API credentials (a service account key).
4. Create a .env file:
In the root of your React project, create a .env file and add your Google Cloud Natural Language API key:
REACT_APP_GOOGLE_API_KEY=your_api_key_here
5. Create a component for sentiment analysis
In the src directory of your React project, create a new file called SentimentAnalysis.js and add the following code:
import React, { useState } from 'react';import axios from 'axios';const SentimentAnalysis = () => {const [text, setText] = useState('');const [sentiment, setSentiment] = useState(null);const analyzeSentiment = async () => {try {const response = await axios.post(`https://language.googleapis.com/v1/documents:analyzeSentiment?key=${process.env.REACT_APP_GOOGLE_API_KEY}`,{document: {type: 'PLAIN_TEXT',content: text,},});setSentiment(response.data.documentSentiment);} catch (error) {console.error('Error analyzing sentiment:', error);}};return (<div><textareavalue={text}onChange={(e) => setText(e.target.value)}placeholder="Enter text for sentiment analysis..."/><button onClick={analyzeSentiment}>Analyze Sentiment</button>{sentiment && (<div><h2>Sentiment Analysis Results:</h2><p>Score: {sentiment.score}</p><p>Magnitude: {sentiment.magnitude}</p></div>)}</div>);};export default SentimentAnalysis;
Line 4–6: Here, we define a functional component called
SentimentAnalysis. This component will render a text area for input, a button to trigger sentiment analysis, and the results of the sentiment analysis.Line 5: This line uses the
useStateHook to create a state variable calledtextand a function calledsetTextto update thetextvariable. The initial value oftextis an empty string ('').Line 6: Here, we create a state variable called
sentimentand a function calledsetSentimentto update thesentimentvariable. The initial value ofsentimentisnull.
Line 8–23: This section defines an asynchronous function called
analyzeSentiment. This function will make an HTTP POST request to the Google Cloud Natural Language API to analyze the sentiment of the text.const response = await axios.post(...);makes an HTTP POST request to the Google Cloud Natural Language API using theaxioslibrary. The URL of the API endpoint is constructed using a template string, and theprocess.env.REACT_APP_GOOGLE_API_KEYvariable is used to include the API key in the request.setSentiment(response.data.documentSentiment);updates thesentimentstate variable with the sentiment analysis results returned by the API.console.error('Error analyzing sentiment:', error);logs an error message to the console if an error occurs during the sentiment analysis.Line 32–40: These lines render a button that triggers the
analyzeSentimentfunction when clicked.{sentiment && ( ... )}uses a conditional rendering pattern to render the sentiment analysis results only if thesentimentstate variable is notnull. The results are rendered as adivcontaining anh2element with the text “Sentiment Analysis Results:”, and twopelements displaying the sentiment score and magnitude.
6. Use the SentimentAnalysis component
In the App.js file, import, and use the SentimentAnalysis component:
import React from 'react';import SentimentAnalysis from './SentimentAnalysis';function App() {return (<div><h1>Sentiment Analysis with Google Cloud Natural Language API</h1><SentimentAnalysis /></div>);}export default App;
Line 2: This line imports the
SentimentAnalysiscomponent from theSentimentAnalysis.jsfile in the same directory as theApp.jsfile. TheSentimentAnalysiscomponent is a functional component that performs sentiment analysis using the Google Cloud Natural Language API.
7. Run the React application
Start the React development server by running the following command in your terminal:
npm start
Try it for yourself
Try running the code given below and try out the sentiment analysis tool yourself. Make sure to replace your API key in the .env file.