score:1

Accepted answer

you could do this a couple of ways, but here is a simple solution. the important part here is to ensure you set your input to a controlled input, where you provide the value from react.

we need a function which will implement your logic. it should take in a string and the total number of commas you want, and limit that string to the comma amount.

below is a very simple function that does this. it splits the string using commas, ensures the result array stays at 10 length, and returns a joined string from the resultant array.

function ensurecommas(str, commas = 10) {
 const commaarray = str.split(',');

 const reduced = commaarray.slice(0, commas);
 
 return reduced.join(',');

}

now to use it. here is a very simple app component which keeps the input value in state and provides this state value to the input, and has an onchange event handler which calls the above function on every key press

import { usestate } from "react";
import "./styles.css";

function ensurecommas(str, commas = 10) {
  const commaarray = str.split(",");

  return commaarray.slice(0, 10);
}

    export default function app() {
      const [value, setvalue] = usestate("");
    
      const oninputchange = (e) => {
        const inputval = e.target.value;
    
        const newinputval= ensurecommas(inputval , 10);
    
        setvalue(newinputval);
      };
    
      return (
        <div classname="app">
          <input value={value} onchange={oninputchange}></input>
        </div>
      );
    }

codesandbox

score:0

remove the handlekeypress function from the input props and update the relationcallbackfunction object.

 const relationcallbackfunction = {
  handleonchangeinput: (e) => {
    let value = e.target.value;
    const currentstr = value.split(",");
    if (currentstr.length <= 10) {
      setrelationsearch(value);
    }
  }
};

Related Query

More Query from same tag