乐闻世界logo
搜索文章和话题

How do I truncate text and display a read more button in React if the text goes past a certain amount of lines?

1个答案

1

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.

jsx
const [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.

jsx
const 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.

jsx
const toggleExpand = () => { setIsExpanded(!isExpanded); };

Step 4: Render the Component

Finally, in the component's return section, display displayText and a button to control expansion/collapse.

jsx
return ( <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:

jsx
import 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.

2024年6月29日 12:07 回复

你的答案