To implement a "show more" component that limits the displayed words instead of characters, you can use the split method to separate the input text into an array of words and then join a portion of that array back into a string.
import React, { useState } from 'react';
const ShowMore = ({ text, wordCount }) => {
const [expanded, setExpanded] = useState(false);
const toggleExpand = () => {
setExpanded(!expanded);
};
const words = text.split(' ');
return (
<div>
{expanded ? (
<>
{words.map((word, index) => (
<span key={index}>{word} </span>
))}
</>
) : (
<>
{words.slice(0, wordCount).map((word, index) => (
<span key={index}>{word} </span>
))}
</>
)}
<button onClick={toggleExpand}>
{expanded ? 'Show Less' : 'Show More'}
</button>
</div>
);
};
export default ShowMore;
i created a component that can count words and added show more button.
import React from 'react';
import ShowMore from './ShowMore';
function App() {
const loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
return (
<div className='app'>
<ShowMore text={loremIpsum} wordCount={10} />
</div>
);
}
export default App;
and you can use it like above.