Created
February 20, 2022 17:38
-
-
Save sunil-bagde/7bd9ce15495d5dd60563e0113239c14b to your computer and use it in GitHub Desktop.
reactjs-limits-chars-perlineand limits-line.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
// https://stackoverflow.com/questions/63597602/javascript-regex-to-limit-number-of-characters-per-line | |
// Regex https://regex101.com/r/lOI5to/1 :- /^.{0,10}(?:\n.{0,10}){0,1}$/ | |
/* | |
.App { | |
font-family: sans-serif; | |
text-align: center; | |
max-width: 400px; | |
} | |
.text-area-name { | |
resize: none; | |
width: 100%; | |
height: 55px; | |
} | |
.counter-limit { | |
padding: 0; | |
margin: 0; | |
width: 100%; | |
display: flex; | |
justify-content: end; | |
align-items: end; | |
} | |
*/ | |
const LimitedTextarea = ({ rows, cols, value, limit }) => { | |
const [content, setContent] = React.useState(value.slice(0, limit)); | |
const [error, setError] = React.useState(""); | |
const setFormattedContent = React.useCallback( | |
(text) => { | |
setError(""); | |
setContent(text.slice(0, limit)); | |
}, | |
[limit, setContent] | |
); | |
return ( | |
<> | |
<textarea | |
onBlur={(e) => { | |
const valid_rx = /^.{0,10}(?:\r?\n.{0,10}){0,1}$/; | |
const text = e.target.value; | |
if (!valid_rx.test(text)) { | |
console.log("Please use correct format."); | |
setError(` | |
Max 2 lines 10 char each line. | |
`); | |
return false; | |
} | |
}} | |
className="text-area-name" | |
rows={rows} | |
cols={cols} | |
onChange={(event) => setFormattedContent(event.target.value)} | |
value={content} | |
/> | |
<p className="counter-limit"> | |
{content.length}/{limit} | |
</p> | |
<p style={{ color: "red" }}>{error}</p> | |
</> | |
); | |
}; | |
export default function App() { | |
return ( | |
<div className="App"> | |
<LimitedTextarea limit={32} value="" /> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment