Skip to main content

Limit number of words or letters in textarea

Video Course With Step By Step Explanation Available on Coding Step By STep Android App

coding step by step android app

Scan the above QR or click on this link

Limited Word Textarea

// App.js
import LimitedWordTextArea from "./LimitedWordTextArea";
import "./styles.css";

export default function App() {
return (
<div className="App">
<h1>Limited Word TextArea</h1>
<LimitedWordTextArea limit={10} />
</div>
);
}
// LimitedWordTextArea.js
import React, { useState, useCallback } from "react";

const LimitedWordTextArea = ({ limit }) => {
const [{ content, wordCount }, setContent] = useState({
content: "",
wordCount: 0
});

const setFormattedContent = useCallback(
(text) => {
let words = text.split(" ").filter(Boolean);
if (words.length > limit) {
setContent({
content: words.slice(0, limit).join(" "),
wordCount: limit
});
} else {
setContent({ content: text, wordCount: words.length });
}
},
[limit, setContent]
);

return (
<>
<textarea
onChange={(e) => setFormattedContent(e.target.value)}
value={content}
/>
<p>
{wordCount}/{limit} Words.
</p>
</>
);
};
export default LimitedWordTextArea;