Open devYuraKim opened 3 months ago
To display only the first 10 words of the children prop in the TextExpander component when it is not expanded, you need to split the children string, extract the first 10 words, and then join them back together. You also need to ensure the rest of the text is displayed when the component is expanded. Here's the updated TextExpander component:
function TextExpander({
collapsedNumWords = 10,
expandButtonText = "Show more",
collapseButtonText = "Show less",
buttonColor = "blue",
expanded = false,
className,
children,
}) {
const [isExpanded, setIsExpanded] = useState(expanded);
function handleClick() {
setIsExpanded((prev) => !prev);
}
// Split the children into words and get the first collapsedNumWords
const words = children.split(" ");
const previewText = words.slice(0, collapsedNumWords).join(" ");
return (
<div className={className}>
{isExpanded ? children : `${previewText}...`}
<span style={{ color: buttonColor, cursor: "pointer" }} onClick={handleClick}>
{isExpanded ? collapseButtonText : expandButtonText}
</span>
</div>
);
}
Changes made:
setIsExpanded((prev)=>!prev)
How can I show only the first 10 words of {children} ?