Search code examples
reactjstextareacounterhighlightuse-state

Dynamically highlight characters after certain length?


I have the following basic React app using the useState hook, which creates a text box and counts the characters users input:

import React, { useState } from 'react';

function App(){

  const [count, setCount] = useState(0); 


  return (
    <div>
      <textarea 
        placeholder="What's happening?" 
        onChange={e => setCount(e.target.value.length)}
      />
      <p>You typed {count} characters</p>
    </div>
  )

}

export default App;

Here is the result, without any styling: enter image description here

My problem now is I would like to highlight characters if the input characters count is greater than 30. As the user types, if the input text exceeds 30 characters, the next characters will be highlighted. If count becomes 31, that one extra character should be highlighted red (or some other color).

I am lost how to achieve this with textarea (and using React).

How would users accomplish this?


Solution

  • well, this is something I did in 10 min, but it works and you can figure the rest out.

    also codeSandBox link

    import React, { useState, useRef } from "react";
    
    const App = () => {
      const [charLength, setCharLength] = useState(0);
      const [inputText, setInputText] = useState("");
      const inputEl = useRef(null);
    
      const maxLength = () => {
        inputEl.current.value = "for something like something something something";
        inputEl.current.setSelectionRange(10, 999);
        inputEl.current.focus();
      };
      return (
        <div className="App">
          <h1>char length: {charLength}</h1>
          <h2>max length: 10</h2>
          <input
            ref={inputEl}
            type="text"
            onChange={(e) => setCharLength(e.target.value.length)}
          />
          <button onClick={() => maxLength()}>Focus the input</button>
        </div>
      );
    };
    
    export default App;