| 1 |
import React, { useState } from 'react'; |
| 2 |
|
| 3 |
const ExpandableContent = ({ content = '', wordLimit }) => { |
| 4 |
const [isExpanded, setIsExpanded] = useState(false); |
| 5 |
|
| 6 |
const toggleExpand = () => { |
| 7 |
setIsExpanded(!isExpanded); |
| 8 |
}; |
| 9 |
|
| 10 |
const truncateContent = (content, wordLimit) => { |
| 11 |
if (!content) return ''; // Handle case where content is not defined |
| 12 |
const words = content.split(/\s+/); |
| 13 |
return words.slice(0, wordLimit).join(' ') + (words.length > wordLimit ? '...' : ''); |
| 14 |
}; |
| 15 |
|
| 16 |
const stripPTags = (html) => { |
| 17 |
if (!html) return ''; // Handle case where html is not defined |
| 18 |
return html.replace(/<\/?p[^>]*>/g, ''); |
| 19 |
}; |
| 20 |
|
| 21 |
const wordCount = (text) => { |
| 22 |
if (!text) return 0; // Handle case where text is not defined |
| 23 |
return text.trim().split(/\s+/).length; |
| 24 |
}; |
| 25 |
|
| 26 |
const displayedContent = isExpanded ? stripPTags(content) : stripPTags(truncateContent(content, wordLimit)); |
| 27 |
const wordCountExceeded = wordCount(content) > wordLimit; |
| 28 |
|
| 29 |
return ( |
| 30 |
<div className="content-sub"> |
| 31 |
<p> |
| 32 |
<span dangerouslySetInnerHTML={{ __html: displayedContent }} /> |
| 33 |
<span onClick={toggleExpand} className="show-more-btn" style={{ cursor: 'pointer' }}> |
| 34 |
{(wordCountExceeded && !isExpanded) && 'Show More'} |
| 35 |
{isExpanded && 'Show Less'} |
| 36 |
</span> |
| 37 |
</p> |
| 38 |
</div> |
| 39 |
); |
| 40 |
}; |
| 41 |
|
| 42 |
export default ExpandableContent; |
| 43 |
|