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;