onclick readmore and readless react js

Onclick Readmore and Readless React JS

If you want to create a read more and read less button in your ReactJS application, you need to use the state to keep track of whether the text is expanded or not. You can create a component that takes in a text prop and renders a truncated version of the text along with a "read more" button. When the user clicks on the "read more" button, the component should expand the text and change the button text to "read less". When the user clicks on the "read less" button, the component should collapse the text back to its truncated version and change the button text back to "read more".

Code Implementation

First, we need to create a state variable to keep track of whether the text is expanded or not:


import React, { useState } from 'react';

function ReadMore({ text }) {
  const [isExpanded, setIsExpanded] = useState(false);
  const toggleExpansion = () => setIsExpanded(!isExpanded);

  return (
    <div>
      <p>
        {isExpanded ? text : `${text.slice(0, 100)}...`}
      </p>
      <button onClick={toggleExpansion}>
        {isExpanded ? 'Read less' : 'Read more'}
      </button>
    </div>
  );
}

export default ReadMore;

In this code, we define our `ReadMore` component that takes in a `text` prop. We use the `useState` hook to create a state variable called `isExpanded` that is initially set to `false`. We also define a function called `toggleExpansion` that will toggle the value of `isExpanded`.

In our `return` statement, we render a `p` tag that displays either the full `text` or a truncated version of the `text` if `isExpanded` is `false`. We use the `slice` method to truncate the text to 100 characters. We also render a `button` that calls `toggleExpansion` when clicked and displays either "Read less" or "Read more" depending on the value of `isExpanded`.

Now, we can use our `ReadMore` component in our application like this:


import React from 'react';
import ReadMore from './ReadMore';

function App() {
  return (
    <div>
      <ReadMore text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam placerat turpis in ante pharetra, ac scelerisque odio commodo. Sed porta velit vitae purus tristique commodo. Sed posuere enim id lacus vehicula, eget commodo tortor vulputate." />
    </div>
  );
}

export default App;

In this example, we render our `ReadMore` component with some sample text.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe