How can I limit the input tag to only 10 Commas?
Solution 1:
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