Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS multiline textarea with ellipsis

I'm trying to build a component with multiline textfield. If the text entered exceeds 2 lines, then I'd like to add the ellipsis (...) for text-overflow.

How can I achieve this by just manipulating the css to show the ellipsis in display only but not modify the actual text that will be stored to contain '...'?

I'm using this React component link

Thanks

like image 597
veggirice Avatar asked Nov 05 '18 14:11

veggirice


2 Answers

I just figured out how to solve this for React.

As Khodor mentioned, line-clamp is what you want. However, it's not currently supported by the official CSS spec. So, you can use -webkit-line-clamp as a sort of workaround. However, I struggled to figure out the exact syntax needed for React. I eventually figured out it out by peeking at the source code for this NPM package react-lines-ellipses and searching for 'webkit' in his github repo.

The React-specific CSS

const textStyle = {
    maxWidth: '100%',
    display: '-webkit-box',
    WebkitBoxOrient: 'vertical',
    WebkitLineClamp: 3,
    overflow: 'hidden',
    textOverflow: 'ellipsis',
  };

I set the maxWidth to ensure the text filled the whole width of the display element. This is optional.

overflow: 'hidden' hides the extra text beyond the 3 lines (I chose 3 at random).

textOverflow: 'ellipses' adds an ellipses (...) to the end of the line, where it gets cut off.

The JSX

<div
    onClick={toggleTruncate}
    style={calculateTextStyle()}
>
This is where my long text goes.
</div>


// This function returns the correct style to the above div.
 function calculateTextStyle() {
    return truncate ? textStyle : null;
  }

// I used React Hooks to create a variable in state to manage if the text should be truncated or not.
  const [truncate, setToggleTruncate] = React.useState(true);

// This function toggles the state variable 'truncate', thereby expanding and truncating the text every time the user clicks the div.
  function toggleTruncate() {
    setToggleTruncate(!truncate);
  }

like image 162
I Stand With Israel Avatar answered Oct 04 '22 17:10

I Stand With Israel


for CSS only, you can use line-clamp, though it doesn't have the best browser support

Check this codepen for implementation.

  display: block; /* Fallback for non-webkit */
  display: -webkit-box;
  max-width: 400px;
  height: $font-size*$line-height*$lines-to-show; /* Fallback for non-webkit */
  margin: 0 auto;
  font-size: $font-size;
  line-height: $line-height;
  -webkit-line-clamp: $lines-to-show;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
like image 33
Khodor Avatar answered Oct 04 '22 18:10

Khodor