DEV Community

David Li
David Li

Posted on • Updated on

How to make a Show More Component in React.

Introduction

Recently I had to make a Show More Component for a body of text. Here I will outline the basic steps to make this component.

  1. Have a truncate text function
function truncateString(str, num) {
  // If the length of str is less than or equal to num
  // just return str--don't truncate it.
  if (str.length <= num) {
    return str
  }
  // Return str truncated with '...' concatenated to the end of str.
  return str.slice(0, num) + '...'
}
Enter fullscreen mode Exit fullscreen mode
  1. Have an internal state variable that tracks if the text should be truncated and likewise use the show more text or the show less text.
import React from 'react';

export type ShowmoreProps = {
  /**
   * Props to be passed to the Showmore component.
   * @params text: string - a node to be rendered in the special component.
   * @params truncateLength: number - the number of characters to show before truncating.
   */
  text: string;
  truncateLength?: number
};

function truncateString(str, num) {
  // If the length of str is less than or equal to num
  // just return str--don't truncate it.
  if (str.length <= num) {
    return str
  }
  // Return str truncated with '...' concatenated to the end of str.
  return str.slice(0, num) + '...'
}

export function Showmore({text, truncateLength = 50}: ShowmoreProps) {

    const [showMore, setShowMore] = React.useState(false);

    if (showMore) {
        return(<div>
          <p>{text}</p>
          <button onClick={() => setShowMore(false)}>Show less</button> 
          </div>
          );
    }
    return (
        <div>
            <p>{truncateString(text, truncateLength)}</p>
            <button onClick={() => setShowMore(true)}>Show more</button>  
        </div>
    );
};
Enter fullscreen mode Exit fullscreen mode

Find more posts like this at my blog

Top comments (2)

Collapse
 
stevegriesel profile image
Stephan Griesel πŸ‡ΏπŸ‡¦ πŸ‡³πŸ‡±

Example would have been nice :)

Collapse
 
friendlyuser profile image
David Li

A little late but its at bit.cloud/friendlyuser/web/showmore will update this article now