Input Field Character Counter in React

Creating a character counter for an input field in a React application is a useful feature, especially for text areas where you want to limit the number of characters a user can enter and show the limit to users.

An input that has the text "Hello world!" and a character count showing 12/100

In this short article, I'll show you how:

Show me the code!

Controlled input

If you are using your state to track the text, the easiest thing to do is show the length of your entered text, like in this first example.

In your React application, create a new component named InputWithCounter.js. This component will render an input field and display the character count:

import React, { useState } from 'react';

function InputWithCounter() {
  const maxLength = 100;
  const [inputValue, setInputValue] = useState('');

  const handleInputChange = (event) => {
    setInputValue(event.target.value);
  };

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onChange={handleInputChange}
        maxLength={maxLength}
      />
      <p>{inputValue.length} / {maxLength}</p>
    </div>
  );
}

export default InputWithCounter;

In this code, useState keeps track of the input field's value. The maxLength attribute limits the number of characters a user can enter. I've used a variable called maxLength to ensure our maxLength and the max value shown is always in sync.

Uncontrolled input

Let's look at a version using an uncontrolled input since it's often the case I see people not tracking their text inputs with state:

import React, { useState, useEffect } from 'react';

function InputWithCounter() {
  const [charCount, setCharCount] = useState(0);
  const maxLength = 100;

  const handleInputChange = (event) => {
    setCharCount(event.target.value.length);
  };

  return (
    <div>
      <input
        type="text"
        onChange={handleInputChange}
        maxLength={maxLength}
      />
      <p>{charCount} / {maxLength}</p>
    </div>
  );
}

export default InputWithCounter;

In this code, the only difference from the first example is that useState keeps track of the input field's length.

All you need to do now is style the component however you like. 💄

Happy coding! ⚡️

REACTJS
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.