React - character counter in real time with a max limit

0 votes
68 views
added Jan 23 in React by lcjr First Warrant Officer (11,830 points)

Here's an example of how you can implement a character counter in real time with a maximum limit of 1000 characters:

import React, { useState } from 'react';

const CharCounter = () => {
  const [inputValue, setInputValue] = useState('');
  const maxCharacters = 1000;

  const handleInputChange = (e) => {
    const inputText = e.target.value;
    if (inputText.length <= maxCharacters) {
      setInputValue(inputText);
    }
  };

  return (
    <div className="right_buddySearch">
      <div className="buddySearch_container">
        <input
          type="text"
          className="buddySearch_input"
          placeholder="Ask us anything..."
          value={inputValue}
          onChange={handleInputChange}
        />
        <div className='char-counter'>{inputValue.length}/{maxCharacters}</div>
        <button className="buddySearch_send">
          {/* <img src="send-icon.png" alt="Send" /> */}
          

1 Response

0 votes
responded Mar 18 by lcjr First Warrant Officer (11,830 points)
const BuddyMain = () => {
  //calling at hook
  const [inputValue, setInputValue] = useState('');
  
  //input handler 
  const handleInputChange = (e) => {
    const inputText = e.target.value;
    if (inputText.length <= maxCharacters) {
      setInputValue(inputText);
    }
  };
  
  //in JSX
    <input
      value={inputValue}
      onChange={handleInputChange}
      css={buddyField}
      className="buddyField"
      type="text"
      placeholder="Ask us anything..."
      onFocus={() => setIsInputFocused(true)}
      onBlur={() => setIsInputFocused(false)}
    />
    <div className="char-counter">
      {inputValue.length}/{maxCharacters}
    </div>

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...