Get a free advice now!

    Pick the topic

    Developer OutsourcingWeb developingApp developingDigital MarketingeCommerce systemseEntertainment systems

    Thank you for your message. It has been sent.

    Tags

    Implementing a character counter in React

    Implementing a character counter in React

    CHALLENGE: set character limit for text area and display current count

    SOLUTION: handle the onChange event, use a Bootstrap badge to display the results

    Sometimes we want to restrict the number of characters that can be written in text input or text area. One solution is to use the HTML5 attribute for form elements, like maxlength. For example:

    <Form.Control as="textarea" maxLength={characterLimit} />

    However, it will be even better to display the current character count and when the limit is exceeded to change the color of a form element to red. We will be using the isInvalid parameter of Form.Control and changing the badge background to danger to emphasize that the limit has been achieved.

    Sample text area

    React Bootstrap

    To have general styles and invalid states already styled, we’re going to install the NPM library with Bootstrap components. Use the following command to install dependency:

    npm install react-bootstrap [email protected]

    And then, import styles in src/index.jsx :

    // src/index.jsx
    import 'bootstrap/dist/css/bootstrap.min.css';

    We use basic Grid elements, Form for displaying textarea and badge for the character counter display.

    Demo in React

    Here is the source code for the main application. When the user is typing in the textarea, we’re updating the inputText value. Having this, we can easily calculate the length (number of characters typed). CharacterLimit is set to 30. An error will appear after exceeding the value.

    // src/App.jsx
    import React, { useState } from "react";
    import './App.css';
    import Container from 'react-bootstrap/Container'
    import Row from 'react-bootstrap/Row'
    import Col from 'react-bootstrap/Col'
    import Form from 'react-bootstrap/Form'
    import Badge from 'react-bootstrap/Badge'
    function App() {
      const [inputText, setInputText] = useState("");
      const [characterLimit] = useState(30);
      // event handler
      const handleChange = event => {
        setInputText(event.target.value);
      };
      return (
        <div className="App">
          <Container>
            <Row className="justify-content-md-center">
              <Col xs lg="3">
                <Form>
                  <Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
                    <Form.Label>Example textarea</Form.Label>
                    <Form.Control as="textarea"  rows={3} value={inputText} onChange={handleChange} isInvalid={(inputText.length > characterLimit)} />
                    <Badge className='mt-3' bg={`${inputText.length > characterLimit ? 'danger' : 'primary'}`}>{inputText.length}/{characterLimit}</Badge>
                  </Form.Group>
                </Form>
              </Col>
            </Row>
          </Container>
        </div>
      );
    }
    Animated preview
    export default App;

    That’s it for today’s tutorial, make sure to follow us for other useful tips and guidelines, and don’t forget to subscribe to our newsletter.

    Do you need someone to implement this solution for you? Check out our specialists for hire in the outsourcing section. Are you considering a global project and are uncertain how to proceed? See how we do it.

    Comments
    0 response

    Add comment

    Your email address will not be published. Required fields are marked *

    Popular news

    Digital marketing without third-party cookies – new rules
    • Technology
    • Trends

    Digital marketing without third-party cookies – new rules

    February 21, 2024 by createIT
    eCommerce healthcheck
    • Services
    • Trends

    eCommerce healthcheck

    January 24, 2024 by createIT
    Live Visitor Count in WooCommerce with SSE
    • Dev Tips and Tricks

    Live Visitor Count in WooCommerce with SSE

    December 12, 2023 by createIT
    Calculate shipping costs programmatically in WooCommerce
    • Dev Tips and Tricks

    Calculate shipping costs programmatically in WooCommerce

    December 11, 2023 by createIT
    Designing a cookie consent modal certified by TCF IAB
    • Dev Tips and Tricks

    Designing a cookie consent modal certified by TCF IAB

    December 7, 2023 by createIT
    Understanding the IAB’s Global Vendor List (GVL)
    • Dev Tips and Tricks

    Understanding the IAB’s Global Vendor List (GVL)

    December 6, 2023 by createIT
    Effortlessly transform JSON data into a clear schema
    • Uncategorized

    Effortlessly transform JSON data into a clear schema

    December 5, 2023 by createIT
    Anatomy of WordPress malware: a technical deep dive
    • Dev Tips and Tricks
    • Technology

    Anatomy of WordPress malware: a technical deep dive

    December 4, 2023 by createIT
    Initializing CMP with the Stub Script and cmpapi.js
    • Dev Tips and Tricks

    Initializing CMP with the Stub Script and cmpapi.js

    November 29, 2023 by createIT

    Support – Tips and Tricks
    All tips in one place, and the database keeps growing. Stay up to date and optimize your work!

    Contact us