How to implement a read more/less feature for long text in React



Image not found!!

Implementing a "Read More/Read Less" feature for long text in React involves toggling between displaying a truncated version of the text and the full text when the user clicks on a button. Here's a basic example of how to implement this feature:

jsx
import React, { useState } from 'react'; const TextComponent = ({ text, maxLength }) => { const [isExpanded, setIsExpanded] = useState(false); const toggleExpand = () => { setIsExpanded(!isExpanded); }; const displayText = isExpanded ? text : text.slice(0, maxLength); return ( <div> <p>{displayText}</p> {text.length > maxLength && ( <button onClick={toggleExpand}> {isExpanded ? 'Read Less' : 'Read More'} </button> )} </div> ); }; export default TextComponent;

In this example:

  • The TextComponent component takes two props: text (the long text to display) and maxLength (the maximum number of characters to display before truncating the text).
  • It uses the useState hook to track whether the text is currently expanded or not.
  • The toggleExpand function toggles the isExpanded state when the user clicks on the "Read More" or "Read Less" button.
  • The displayText variable holds either the full text or the truncated text based on the current state.
  • If the length of the text exceeds the maxLength, a button is rendered to allow the user to toggle between displaying the full text and the truncated text.

You can use this TextComponent in your application wherever you need to display long text with a "Read More/Read Less" feature. Adjust the maxLength prop to control how much text is displayed before it is truncated.