Skip to main content

limited-word-textarea-in-react

· One min read
// 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;