Read More/Read Less button in ReactJS

The “Read More/Read Less” button is a common feature in many websites and applications, which allows users to expand or collapse text content based on their preferences.

In this explanation, we’ll discuss how to implement this feature in React JS.

Read More/ Read Less button in ReactJS

Here are the steps to create a “Read More/Read Less” button in React JS:

  1. Create a state variable to track whether the text is expanded or collapsed. We can use the useState hook to create this state variable and initialize it to false, which means that the text is initially collapsed.
import { useState } from "react";

function App() {
  const [isExpanded, setIsExpanded] = useState(false);
  //...
}

Render the text content using a p tag, and conditionally render the “Read More” button based on the state variable.

If the text is collapsed, we’ll only show the first 100 characters of the content, followed by the “Read More” button. If the text is expanded, we’ll show the entire content, followed by the “Read Less” button.

function App() {
  const [isExpanded, setIsExpanded] = useState(false);
  const content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";

  return (
    <div>
      <p>{isExpanded ? content : `${content.slice(0, 100)}...`}</p>
      {isExpanded ? (
        <button onClick={() => setIsExpanded(false)}>Read Less</button>
      ) : (
        <button onClick={() => setIsExpanded(true)}>Read More</button>
      )}
    </div>
  );
}

Add event handlers to toggle the state variable when the “Read More” or “Read Less” button is clicked.

We can use the onClick attribute to add event handlers that toggle the Expanded state variable between true and false.

function App() {
  const [isExpanded, setIsExpanded] = useState(false);
  const content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";

  const handleExpandClick = () => {
    setIsExpanded(true);
  };

  const handleCollapseClick = () => {
    setIsExpanded(false);
  };

  return (
    <div>
      <p>{isExpanded ? content : `${content.slice(0, 100)}...`}</p>
      {isExpanded ? (
        <button onClick={handleCollapseClick}>Read Less</button>
      ) : (
        <button onClick={handleExpandClick}>Read More</button>
      )}
    </div>
  );
}

And that’s it! With these steps, we have created a “Read More/Read Less” button in React JS that allows users to expand or collapse text content based on their preference.

Leave a Comment