2

I want to create a showMore component. I want that my component gets the word count prop and show just that amount of words when the paragraph is collapsed.

I used substring method, but it is just for characters and I don't know how to implement is for words.

M9heb
  • 21
  • 3

1 Answers1

1

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.

Yash Parekh
  • 115
  • 8