Implementing text truncation and adding a "Read More" button in React can typically be done through the following steps:
Step 1: Define Component State
First, define a boolean variable in the component's state to indicate whether the text is fully displayed. Name it isExpanded.
jsxconst [isExpanded, setIsExpanded] = useState(false);
Step 2: Text Truncation Logic
Next, define the text and truncation logic. Assume you have a variable text storing the full content; create a variable displayText that shows the full text or a portion based on isExpanded.
jsxconst MAX_LINES = 3; // Example: displaying 3 lines const text = "This is a sample long text..."; // Full text content let displayText = isExpanded ? text : text.split("\n").slice(0, MAX_LINES).join("\n") + "...";
Here, the split and slice methods truncate the text. Note that "\n" serves as the line delimiter, which depends on how your text is structured.
Step 3: Toggle Expand/Collapse State
Define a method to toggle the isExpanded state, controlling text display.
jsxconst toggleExpand = () => { setIsExpanded(!isExpanded); };
Step 4: Render the Component
Finally, in the component's return section, display displayText and a button to control expansion/collapse.
jsxreturn ( <div> <p>{displayText}</p> <button onClick={toggleExpand}> {isExpanded ? "Read Less" : "Read More"} </button> </div> );
Complete Example
Integrating the above, here is a full React component:
jsximport React, { useState } from 'react'; function ReadMoreComponent({ fullText }) { const [isExpanded, setIsExpanded] = useState(false); const MAX_LINES = 3; let displayText = isExpanded ? fullText : fullText.split("\n").slice(0, MAX_LINES).join("\n") + "..."; const toggleExpand = () => { setIsExpanded(!isExpanded); }; return ( <div> <p>{displayText}</p> <button onClick={toggleExpand}> {isExpanded ? "Read Less" : "Read More"} </button> </div> ); } export default ReadMoreComponent;
Use <ReadMoreComponent fullText="your long text..." /> anywhere to implement the "Read More" functionality.