trainReact.com
||

4. Character Counter for Text Input and Limit value

Easy
Category: State Management
inputState ManagementuseStateString Manipulation

Problem Description

You are given a React component CharacterCounter that renders an input field and displays a character count.

Your task is to implement the functionality where the input is limited to a maximum number of characters, and the current character count is displayed and updated as the user types.

Requirements:

  1. Create a functional React component named CharacterCounter.
  2. Below the input field, display the current character count and the maximum allowed characters in the format "X / Y" (where X is the current count and Y is the maximum).
  3. Set the maximum character limit to 20.
  4. Prevent the user from typing more characters once the limit is reached.
  5. Update the character count in real-time as the user types.
  6. Spaces should be counted as characters.
  7. The component should handle backspace and pasting of text correctly.

Constraints

  • Do not modify the existing JSX structure or data-testid attributes.
  • Use the provided data-testid attributes for the input field ('input') and the paragraph displaying the character count ('char-count').
  • The maximum character limit is defined as a constant in your component with a value of 20.

Example:

  • Normal input: If the user has typed "Hello, World!" (13 characters), the display should show:
1[Input field with "Hello, World!"]
213 / 20
3
  • Normal input: If the user has typed " Hello, World! " (15 characters), the display should show:
1[Input field with " Hello, World! "]
215 / 20
3
import React, {useState} from 'react';

const CharacterCounter = () => {
  const [inputValue, setInputValue] = useState('');
  const maxChars = 20;

  return (
    <div>
      <input
        data-testid="input"
        type="text"
        value={inputValue}
      />
      <p data-testid="char-count">0 / {maxChars}</p>
    </div>
  );
};

export default CharacterCounter;

Open browser consoleTests