Home > database >  How to count each character from the textarea using react and display total count?
How to count each character from the textarea using react and display total count?

Time:11-02

I am new to react and I am trying to count each character from textarea and display the character count. I have done total character count but How do I count each character and display number of character ? My code is follows :

import React, { useState } from "react";

function Home() {
  const [characterCount, setCharacterCount] = useState(0);

  const myFunction = (e) => {
    e.preventDefault();
    console.log("clicked");
  };
  return (
    <div>
      <form onSubmit={myFunction}>
        <h3>Please enter text</h3>
        <textarea
          onChange={(e) => setCharacterCount(e.target.value.length)}
          placeholder="start typing"
        ></textarea>
        <div>
          <button type="submit">submit</button>
        </div>
        <p>Total number of character :{characterCount}</p>
      </form>
    </div>
  );
}

export default Home;

output: user input

    abbbsewrrrrree
Total number of character : 14

Expected: Example: if user input:

abbbsewrrrrree

a=1
b=3
s=1
e=3
w=1
r=5

CodePudding user response:

I think you should make the input(textarea) controlled, as you would like to process the value (to count each character). Edit react-count-each-character

  • Related