AI can perform sentiment analysis by using natural language processing models to classify text as positive, negative, or neutral based on emotional tone.
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.
ãF ) 95@@ °nPNG IHDR(-SäPLTE""""""""""""""""""2PX=r)7;*:>H¤-BGE8do5Xb6[eK®K¯1MU9gs3S\I§:gt'03@{V¹ÔT´ÏA}V»Ö@y6\fH¦-CII¨E+;@7_i7_jFJ«K°H£-BHaÚû,@FCL³&.0W½ÙN£ºI¨$)+BJªR¯È?v>s>uS±Ê=qP©ÁP¨ÀP§¿,?D4U^%+-M ¶K®%+,2OX+<AL²#&&D%,.I©vôTötRNSIæçJäeÀe¦©IDATxMµZEAÿÙ³ îî%R¡ïßáTThÇG »,Á®Å=²ÒîmífímnfA$â>!¦gºôHg½Eßܵ} Ý»ýº¼kdú§¯JoÎ3æL"J¹ ÌÕüQ$âçļffµ,é5i9̯H¨/mBwÍÜw;D Ø+&W«ª¹¨Dôo@Ê´RI©ÐB¡om.Û³ÀIEND®B`PNG IHDRשÍÊePLTE""""""""""""""""""""""""2RZN¢¹J«3R[J¬)59YÁÞ0KS4W`Q«ÄL²%+-0JR)6::gtC"##?vU·Ñ?w<n{&-/YÂß=q:iuBA}A{B/IPP§¿=qK®_ÔóL³$();lzR¯ÉaÚûI¨ZÆã3U^1MU3T]ZÅâI§X¿ÜF-BGP¨À6[e,@E5ZdO§¿-BHX¿Û+=AW¾Ú,@FW¼ØQªÃ?v W¼×+<A@y"#$\Ìê4Wa\ÌëS²Ì$(*.EL^ÑñVºÕ6]h#$%G¡#&';jwV¹Ô-CIL±ZÄá^Ðï>uS°Ê/HNM ·_Õõ\ËéM ¶8doD D>t+=B[Èæ,>C>t<o}@y0LS.EKT´Î$'(%,.A~W½ÙC%+,\ÊèC!ätRNSíîG¾ÖOIDATxlÃB¶Q u´ß_ȳ<˦Ýveê²óa6Aξûv¢{@ÎE'ÞdIÕ!çí ðCÔTþg1ÂE(ÏñSQsâi Ä Zÿ·V¹Ð)ég!ªhÎùtéº-i}µµ<Õ?¶lBZaÄ´4{DÓâ»_e8¥yÇÀ3)¥?°f;8.ã¤tÌ=å; :ã52fKZìlù¨ØÍ9.#ÒAÁqÌúÛ®£Vÿ`=$¬Â?_¶¾®ÔqMç.ïJ$ ?^q÷ñíÛï.},ìsæÝ_TttÔ¾1#/(ì-[è`è`ÌÚïÅðZd5?ÎebZ¿Þi.ÛæìqÎ+1°}Â5ùïçd¨GÏøIEND®B`PNG IHDR D¤ÆAPLTE"""""""""""""""""""""""""""2RZVºÖ_ÔôU·Ñ=r$()'25]ÎíC0LS<o}XÀÜX¿Û0JQ=p~D<n{VºÕE8do_ÔóEFH¥9dp_ÕõH¤I¨F6[e`Ö÷`×øL³/GM_ÓòU¸Ó'02P©Á/IPPªÂX¿Ü&/1;ly3R[`ØøG¡T³Í\ÌêaÚû1OW"##Q«ÄaÙúR®Ç=q`Öö.EL+=ATµÐ-CIK®#&'C^ÐïI¨&.04U^^Ñð@yZÇä$(*[Éç^Ññ,?DR¯É"#$1NV1MTD >u;kxG R¯È/HN&-/@y>s>t@z]ÍìP¨À$'(D]Ïî<n|0JRU·Ò×\¼ tRNS%ñ'ïó(ò~ÑÝèIDATxC1F_Ý¿MmÛ¶4¶m{ÿ¤nçáÓ ®A$à$b HeøTãWÄÂhh´:PtZ Q«0@.`Þ`4-V`³Zì&A#ÁébkÝÄãñúØ>.''ø`C$FØÏ (±x"6XácTÚéL§@Iù;dd-¹|¾P,È9¡RÕÍf3¢¿F½VmMíX§ÚíÍç@Y7ÎõºÕN¬=åÈʪu }Ö¬«+eaiq ¤Ö76íÝ=h ûZìíîlë}á¨Ê±¥[F«I9A¹k9¥Öëä3¢Ã9ΡóqB~Øáb¸ÃåU_¸^Ü[·ôwý{zvzÙ(£(£(þfòqÉGÉïkñÏçY¾ÿªfäòÇ~à:*4ÓQ\O> ¼<×úW£éÍZ|ÞÅ7ñïjTÔäãn½»¢®`$Hð+ò¿GOñûð*èxø¥X*|^ÿdIEND®B`PNG IHDR@@·ì:PLTE"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""%+-@yW¼×`×ø^ÑñS²ÌC,>C*8<XÁÝaÚûaÙùMµ+<AaÙúXÀÜ#%%TµÐL´=q>uK°`ÖöA}L±8do=r%+,@y^ÐïS²Ë)59=qP©ÁU·Ò"#$PªÂ\Êè0JQQªÃ"##U·Ñ#&&_Ôô>t>s`Øø_Ôó5Yc1OW5Zd1NV+=B1MU+;@/GM\Ìê*;?3S\)8<2RZ_Õõ+=A]Ïî,@F,@E&-/0KS7alO¦¾9dp8amB~EP¨ÀN¢¹'023T]]Îí?x3U^C6\gU¸Ó&.0D7_iRÆH¥I¨M ¶$(*?v ZÆãX¿Ü-AG#$%[Éç8co[ÈæW½ÙC'25?v8bn%*+L²N£º2PX)7;=p~(58^ÒòP§¿4WaQ«ÄT´Ï0JRQ¬ÅT´ÎI¨6]hR¯ÉT³Í0LSF9eqEE9gsFC#&'\Ëé`Ö÷&/16\fBA{R®Ç]Íì(47%,.*:>*9=9fr:gt7^iU¶Ð?wZÇäX¿Û^ÑðQÅH£)6:V¹Ô'034U^E.EL.FMK®@zS×tRNS*×øÖý »½+üùóÔ,ØúôÀ=VIDATx¤ËµC!ÐïC|ÿãÚ^yR]ÕMÛáO]ßÔÕÝ0NÈ2ÍËí¿"ªª¢(0Vã(ÀY%PDT-~(m¬ó!âKÞY£~´üIÒf{³ÛÞáa¼§§ô3ÕOp&Ф¡x÷#jôÚ¶mméòc)]m¤É)Ƨgfçhk²ñÎÒ ægg¦ÇìÐ+XÅêuiyVת·k«°²\[ü:,Ø6ØÜjIJ ;»"»;°×XùþÛfÁáÇÍûýSÎÎÏÏ8=Þo¾;æèÐ(öÓ¥BkÔeûÍ\7p+mîîáþNÚ<ÀQðOÒæùô³´yg»ttÐëoý½£ìVð»Òäsýü¬ø&_ðaüïV~à·Ö?*8àQ ;8¥Á,¸¤f¥1Üx¤×§ñ*øÑA¯Ôð°a#±³¶¦#nPi+¼¶CÈ,ÆèäÍ_áNbÑáøçHB*ÚÒ¦ L(^<ñÃL6pJ¾PÉ¥©¢%"R,ä9Èe3eRËa1( ¢ßqÇ8Ù´mK˱mƶmÛü·yi!èΪYÏuë ÀÏ_Àï?i÷ý+òÄA|ù{´?¿_En).JËD¤< ©¬¢Z\Ts©R*( ¯©J uX/ 4J9¡5·DEµ4kÇ4&i¥V4Ú¡®Ð¯vsf:àg,¢èBC»î$¶ºÍùîá@ôI_?<!^ÈàÓ½ÇöäõB%Làw±FD1Á¨(F±øH%0Ʊ¿ÅØ(¢0ÅÄ'ÅæN.0u@íYPWìIüaNâKÄ?ðÓµ=ev/c±Ó0c0÷2Êë:06R-uÒÄ\Q̶ää´¼µ6R# ÆF³6Òñ·rÕìuæmâðÂIñi~ Åü ÃsPþ"±ó¼ eiyå£ËPàãÊò§¡ÝÒ,S]U¦ºV ªÖ©®Z¦êoëë·xzãâÆSnm¬{ÚºwaÙÏ Å»´Ýõ(mg/®þå½À¿¼û[§b³µq¶Å&Õ¯¹$ñzÈH>aÌKT1/æø1O0¾.hÍYþAÓö£ -ê>Ûº«¢XÕ¢î}ߨëÛÑ;ÃöN´ØvÅýθÿ1ë×ÄO@&v/Äþ_ö\ôÇ\í.½+0;!fʦ´Ó% JY·OÂ'/Å]_;ßÀ'"&Nªn aQ^cx¦AáÒIEND®B`
With this setup, you’ve successfully created a basic sentiment analysis tool in React that leverages AI through the Google Cloud Natural Language API. This tool allows users to input text and receive immediate feedback on the sentiment, providing insights into the tone and emotion conveyed. Integrating AI into front-end applications can enhance interactivity and add powerful features, making your applications smarter and more responsive to user needs.
This implementation also demonstrates how easily accessible AI-powered features can be by utilizing cloud APIs, enabling even small-scale applications to harness advanced natural language processing capabilities. From here, you could extend the functionality by adding language detection, entity recognition, or even saving user feedback for more in-depth analysis. Experiment with other Google Cloud API features to expand your application’s scope and bring even more value to your users!
Haven’t found what you were looking for? Contact Us
Free Resources