Sentiment Analysis App With React
Tags: react, npm, beginners, programming
Published: 2020-12-27 15:14:29

In this digital world where everyone is sharing their thoughts online, it's necessary to know how your content impacts the readers. 


> The first duty of an editor is to gauge the sentiment of his reader, and then to tell them what they like to believe.        
  ~ Thorstein Veblen

In this article, I'll show you how to create a simple React App for *Sentiment Analysis* using the  [react-sentiment package](https://www.npmjs.com/package/sentiment) 

### Prerequisite

- Basic knowledge of React
- Text-editor of your choice

## Step 1: Create React App

Create your React App using the command:

```javascript
npx create-react-app sentiment-analysis-app

``` 

This will result in the following folder structure:

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1608840105192/LkBWZHJTq.png)

## Step 2: Install npm package

Install npm sentiment package 


```javascript
npm install sentiment --save
``` 

## Step 3: Add Input text field

Go to the `src/App.js` file and replace the existing code with the following:


```javascript
import React, { useState, useEffect } from 'react';
import './App.css';

function App() {

  const [phrase, setPhrase] = useState('');
  
  return (
    <div className="App">
      <header className="App-header">
        <h2>Sentiment Analysis</h2>
        <input value={phrase} onChange={e => setPhrase(e.target.value)}
          style={{ padding: '20px', fontSize: '20px', width: '90%' }} />
      </header>
    </div>
  );
}

export default App;

``` 

## Step 4: Add Sentiment Component


```javascript
import Sentiment from 'sentiment';
const sentiment = new Sentiment();

``` 
Import the 'sentiment' package, which you install earlier into your file.

Now, when the user types anything in the Input text field we need to check the sentiment score. 


```javascript
  const [sentimentScore, setSentimentScore] = useState(null);

useEffect(() => {
    setSentimentScore(sentiment.analyze(phrase));
  }, [phrase]);

``` 

In the above code, we have created an initial state of sentiment score and after any change in a phrase, it will update the sentiment score. 

Now, display sentiment score using:

```javascript
{
          sentimentScore ?
          <p>Sentiment Score: {sentimentScore.score}</p>
          : ''
 }

``` 

## Step 5: Change Images based on Sentiment score

Add the images of your choice inside the `src/images` folder which represent "happy", "sad" & "neutral" behavior. 

Now display the different images based on sentiment score.


```javascript
{
          sentimentScore ?
            sentimentScore.score === 0 ?
              <img src={neutralGIF} alt="neutral" />
              :
              sentimentScore.score > 0 ?
                <img src={positiveGIF} alt="postive" />
                :
                <img src={negativeGIF} alt="negative" />
            : ''
        }
``` 

## Final Code

Your final code in `src/App.js` file will look like this:


```javascript
import React, { useState, useEffect } from 'react';
import './App.css';
import positiveGIF from './images/positive.gif';
import negativeGIF from './images/negative.gif';
import neutralGIF from './images/neutral.gif';

import Sentiment from 'sentiment';
const sentiment = new Sentiment();

function App() {

  const [phrase, setPhrase] = useState('');
  const [sentimentScore, setSentimentScore] = useState(null);

  useEffect(() => {
    setSentimentScore(sentiment.analyze(phrase));
  }, [phrase]);

  return (
    <div className="App">
      <header className="App-header">
        <h2>Sentiment Analysis</h2>

        <input value={phrase} onChange={e => setPhrase(e.target.value)}
          style={{ padding: '20px', fontSize: '20px', width: '90%' }}
        />

        {
          sentimentScore !== null ?
            <p>Sentiment Score: {sentimentScore.score}</p>
            : ''
        }

        {
          sentimentScore ?
            sentimentScore.score === 0 ?
              <img src={neutralGIF} alt="neutral" />
              :
              sentimentScore.score > 0 ?
                <img src={positiveGIF} alt="postive" />
                :
                <img src={negativeGIF} alt="negative" />
            : ''
        }

      </header>
    </div>
  );
}

export default App;

``` 


## Demo


Start your application on localhost:3000


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1608893134970/HOI39xKSj.png)



![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1608893170552/0Yr7SGN8z.png)


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1608893199593/VGQuoovLi.png)


## Wrap Up

Thank you for reading. I hope you enjoyed reading it. Please share it with your network. Don’t forget to leave your comments below.