小能豆

Display a short version of long string on a div in React TS

javascript

I am working on a React component that receives a long string and a numerical variable as props. The component’s objective is to display a trimmed version of the string, based on the specified number variable. Additionally, it should include “show more” and “show less” buttons.

Despite attempting various approaches, none have proven successful. The original single-line string becomes multi-lined when placed within a div with defined width and height. My primary challenge arises when using the “useRef” hook to access textRef.current.innerHTML, which returns the original string without ‘\n’ characters.

Do you have any suggestions on how to address this issue?


阅读 81

收藏
2023-11-30

共1个答案

小能豆

If you’re using innerHTML, it will not retain the original formatting, and newline characters won’t be translated into line breaks. To display a trimmed version of the string while preserving line breaks, you might want to consider a different approach.

One way to achieve this is to use the white-space: pre-line CSS style, which preserves both spaces and newline characters. This way, you can use the slice method to trim the text based on the specified number of characters while keeping line breaks intact.

Here’s an example of how you could implement this in a React component:

import React, { useState } from 'react';

const TextTrimmer = ({ text, trimLength }) => {
  const [isExpanded, setIsExpanded] = useState(false);

  const trimmedText = isExpanded ? text : text.slice(0, trimLength);

  return (
    <div style={{ whiteSpace: 'pre-line' }}>
      {trimmedText}
      {!isExpanded && text.length > trimLength && (
        <button onClick={() => setIsExpanded(true)}>Show more</button>
      )}
      {isExpanded && (
        <button onClick={() => setIsExpanded(false)}>Show less</button>
      )}
    </div>
  );
};

export default TextTrimmer;

In this example, the whiteSpace: pre-line style ensures that newline characters are respected, and the slice method is used to trim the text based on the specified length. The “Show more” and “Show less” buttons allow the user to toggle between the trimmed and full text.

You can use this component like this:

<TextTrimmer
  text="Your long string with\nmultiple lines\nof text."
  trimLength={50}
/>

Adjust the trimLength prop based on your specific requirements.

2023-11-30