DEV Community

Victor Novais
Victor Novais

Posted on

React Hooks: creating a char counter component

Hello fellow readers!

In this article I am going to show you how to build a simple char counter component that can be used anywhere, for example on a simple text input or even a text area!

The final result is the following:

A text input that has a char counter next to it, showing the current text length and the max length. The counter becomes red once the current length is greater than the max one.

The char counter component

Let's start with this simple component. This is going to be a stateless component that just receives the current count and the total count.



type CharCountProps = {
  current: number;
  total: number;
};

const CharCount = ({ current, total }: CharCountProps) => {
  return (
    <span style={{ color: current > total ? 'red' : 'black' }}>
      {`${current}/${total}`}
    </span>
  );
};


Enter fullscreen mode Exit fullscreen mode

As you can see, I also applied a color style to change the text to red if the current count is greater than the total.
Now let's apply this component to a text input!

Applying to a text input

We are now creating the text input that will hold the CharCount component.
To make it flexible, this custom input has a maxLength prop that tells us how many characters are allowed.
Also, our CharCount component is only going to render if this prop is different from undefined.

Note below that the input onChange handler updates the value state, which length property is used on CharCount.



type CustomInputProps = {
  maxLength?: number;
};

const CustomInput = ({ maxLength }: CustomInputProps) => {
  // This state holds the input's text
  const [value, setValue] = useState<string>('');

  return (
    <fieldset>
     {/* Here is our input that is being watched */}
      <input
        type="text"
        value={value}
        onChange={(e) => setValue(e.currentTarget.value)}
      />

      {/* The char counter only renders if the maxLength prop is provided */}
      {maxLength !== undefined && (
        /* The CharCount component receives the current string length and the max length supported for this field */
        <CharCount current={value.length} total={maxLength} />
      )}
    </fieldset>
  );
};


Enter fullscreen mode Exit fullscreen mode

Wrapping up

Lets now just create a CustomInput with a defined maxLength:



export default function App() {
  return <CustomInput maxLength={10} />;
}


Enter fullscreen mode Exit fullscreen mode

This renders an input with a char counter validation! You may now add some behavior, like alerting the user that the input content cannot be greater than the expected.

Here we used a simple useState hook to hold our input's data and pass it further to the CharCount stateless component.

You may find the complete code clicking here.

That's it for now! I hope you all enjoyed it!
Feel free to use the comment section below to share your ideas!

Top comments (0)