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.
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
Next, install the necessary dependencies for making HTTP requests and handling environment variables:
npm install axios dotenv
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).
.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
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 useState
Hook to create a state variable called text
and a function called setText
to update the text
variable. The initial value of text
is an empty string (''
).
Line 6: Here, we create a state variable called sentiment
and a function called setSentiment
to update the sentiment
variable. The initial value of sentiment
is null
.
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 the axios
library. The URL of the API endpoint is constructed using a template string, and the process.env.REACT_APP_GOOGLE_API_KEY
variable is used to include the API key in the request. setSentiment(response.data.documentSentiment);
updates the sentiment
state 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 analyzeSentiment
function when clicked. {sentiment && ( ... )}
uses a conditional rendering pattern to render the sentiment analysis results only if the sentiment
state variable is not null
. The results are rendered as a div
containing an h2
element with the text “Sentiment Analysis Results:”, and two p
elements displaying the sentiment score and magnitude.
SentimentAnalysis
componentIn 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 SentimentAnalysis
component from the SentimentAnalysis.js
file in the same directory as the App.js
file. The SentimentAnalysis
component is a functional component that performs sentiment analysis using the Google Cloud Natural Language API.
Start the React development server by running the following command in your terminal:
npm start
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.