Word Counter with React

share link

by vsasikalabe dot icon Updated: Feb 22, 2023

technology logo
technology logo

Solution Kit Solution Kit  

To display the count of words, the Word count is used. First, we must initialize the total number of words in the box. Based on this, we must write the sentence. The sentence will stop after the point. We use the first handle, the handle submits, and the second handle. Limwords will give us limited words. If we type extra words, the error will be shown like 'you exceeded the maximum no of words'.If we type fewer words, the hint will be 'you still have to write (result) words'. 


The number of words and characters (including whitespace) will be displayed when you type some text into this text area. When the user types something into the text area using the input event handler on the text area, the countWord() function is called every time.  

While you are typing a word, count the number of words in a document. This also counts pages, paragraphs, lines, and characters. This method is used when you need to know how many words, pages, characters, paragraphs, or lines are in a document. Suppose the loop is used to check the status of the word count. This method satisfies our conditions to fill the text in the text area as required.  

  • In real-time, the Word Counter is a tool for counting words, characters, sentences, and paragraphs, while you type.  
  • This method calculates the reading time of your text. 
  • Its readability score helps improve the content of your website, essay, or document. 


Here is an example of how to create a word counter using Reactjs: 

Preview of the output that you will get on running this code from your IDE.

Code:

In this solution we use the React library.

   class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      firstValue: "",
      secondValue: "",
      needWords: "",
      wordCount: "",
      limWords: null
    };
    this.firstHandle = this.firstHandle.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.secondHandle = this.secondHandle.bind(this);
  }
  firstHandle(e) {
    this.setState({
      firstValue: e.target.value
    });
  }

  handleSubmit(e) {
    e.preventDefault();
    this.setState({
      needWords: this.state.firstValue,
      secondValue: ""
    });
  }

  secondHandle(event) {
    //calculate the word count first itself and use them in other manipulations
    const wordCount =
      event.target.value === "" ? 0 : event.target.value.split(" ").length;
    this.setState({
      secondValue: event.target.value,
      wordCount: wordCount,
      limWords:
        this.state.needWords - wordCount < 0
          ? this.state.secondValue.length
          : null
    });
  }

  render() {
    var result = this.state.needWords - this.state.wordCount;
    let tooManyChars;
    if (result < 0) {
      const tooManyCharStyle = {
        color: "red"
      };
      tooManyChars = (
        <p style={tooManyCharStyle}>
          You exceeded the maximum number of words!!
        </p>
      );
    }
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <p>How many words do you have to write?</p>
          <input
            type="text"
            value={this.state.firstValue}
            onChange={this.firstHandle}
          />
          <button type="submit">Go</button>
        </form>
        <form>
          <p>You still have to write {result} words</p>
          <textarea
            type="text"
            value={this.state.secondValue}
            onChange={this.secondHandle}
            maxLength={this.state.limWords}
          />
          {tooManyChars}
        </form>
      </div>
    );
  }
}

Instructions

Follow the steps carefully to get the output easily.

  1. Install the Node.js and React on your IDE(preferable Visual Studio Code).
  2. Create React Application using npx create-react-app foldername.
  3. cd foldername.
  4. Open the folder in IDE.
  5. Copy the code using "copy" button above and paste it in App.js file(remove the earlier code from App.js).
  6. Import React and React-Dom.
  7. Add const rootElement = document.getElementById("root"),ReactDOM.render(<App />, rootElement),export default App to the end of the line.
  8. Open the terminal from IDE.
  9. npm start to run the file.


You can also refer this url DEMO for getting the above output.

I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.


I found this code snippet by searching for Word Counter with React in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in VS Code 1.73.1 version.
  2. The solution is tested on Nodejs 16.14.2 version.
  3. react 18.2.0 version.


Using this solution, we are able to do Word Counter with React with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to do Word Counter with React.

Dependent Libraries

create-react-appby facebook

JavaScript doticonstar image 100082 doticonVersion:v5.0.1doticon
License: Permissive (MIT)

Set up a modern web app by running one command.

Support
    Quality
      Security
        License
          Reuse

            create-react-appby facebook

            JavaScript doticon star image 100082 doticonVersion:v5.0.1doticon License: Permissive (MIT)

            Set up a modern web app by running one command.
            Support
              Quality
                Security
                  License
                    Reuse

                      You can search for any dependent library on kandi like react.

                      Support

                      1. For any support on kandi solution kits, please use the chat
                      2. For further learning resources, visit the Open Weaver Community learning page.

                      See similar Kits and Libraries