Creating a multiline textarea with ellipsis using ReactJS

Looking to create a component with a multiline textfield that displays ellipsis (...) for text overflow beyond 2 lines. How can I achieve this through CSS only without modifying the actual stored text?

Utilizing the React component found at: link

Appreciate any assistance, thank you.

Answer №1

After some experimentation, I successfully found a solution for handling this in React.

As mentioned by Khodor, using line-clamp is the way to go. However, since it's not officially supported in CSS yet, a workaround like -webkit-line-clamp can be used. I had some difficulty figuring out the correct syntax for React at first. Eventually, I managed to uncover it by examining the source code of the NPM package react-lines-ellipses and searching for 'webkit' within the GitHub repository.

The Custom CSS for React

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

I specified the maxWidth to ensure the text fills the entire width of the displaying element, though this step is optional.

overflow: 'hidden' conceals any surplus text beyond the set 3 lines (I arbitrarily selected 3).

textOverflow: 'ellipsis' appends an ellipsis (...) to indicate where the text has been truncated.

The JSX Implementation

<div
    onClick={toggleTruncate}
    style={calculateTextStyle()}
>
This area contains my lengthy text.
</div>


// The following function determines the appropriate style for the above div.
 function calculateTextStyle() {
    return truncate ? textStyle : null;
  }

// By using React Hooks, I established a state variable to control whether the text should be truncated or displayed in full.
  const [truncate, setToggleTruncate] = React.useState(true);

// This function toggles the state variable 'truncate', providing a mechanism to expand or truncate the text with each click on the div element.
  function toggleTruncate() {
    setToggleTruncate(!truncate);
  }

Answer №2

If you're looking to achieve a text truncation effect using just CSS, one option is to utilize the line-clamp property. Keep in mind that this feature may not be fully supported across all browsers.

For a practical demonstration, refer to this CodePen example.

  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;

Answer №3

To achieve this functionality in JavaScript, you can use the following code snippet. It involves splitting the input value into lines and wrapping additional lines in parentheses if there are more than one.

If you are working with a React component that includes an onChange prop, you may consider implementing a similar approach for handling user input.

const textAreaElement = document.getElementById('t')

textAreaElement.addEventListener('keyup', () => {
  const value = textAreaElement.value.replace(/[\(\)]/g, '')
  const splitLines = value.split(/(?:\r\n|\r|\n)/)
  
  const newValue = splitLines.length > 1 ?
    `${splitLines[0]}\n(${splitLines.slice(1, splitLines.length).join('\n')})` : splitLines[0]
  
  textAreaElement.value = newValue;
  
});
<textarea id="t"></textarea>

Answer №4

If you're looking for an easy way to implement multi-line ellipsis, consider utilizing the antd typography component. Simply add a prop called ellipsis and specify the number of rows after which the text should be truncated.

<Paragraph ellipsis={{ rows: 3, expandable: true }}>
  Ant Design, a design language for background applications, is refined by Ant UED Team.
  Ant Design, a design language for background applications, is refined by Ant UED Team.
  Ant Design, a design language for background applications, is refined by Ant UED Team.
  Ant Design, a design language for background applications, is refined by Ant UED Team.
  Ant Design, a design language for background applications, is refined by Ant UED Team.
  Ant Design, a design language for background applications, is refined by Ant UED Team.
</Paragraph>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transform the text upon hovering over the image, with the text positioned separate from the image

I'm looking for a solution where hovering over images in a grid area will change the text on the left side of the screen to display a predefined description of that image. I've been working on this problem for hours and would appreciate any help. ...

Is there a way for me to store the message I sent using discord.js in a variable?

I'm looking to send a message in the channel and then react to it by getting that message for a message reaction. bot.sendMessage({ to: channelID, message: '@everyone\n' + message.slice(16) + '\n\nThis message is a ...

Changing the text color in React Native WebView

When I have a string of HTML that needs to be shown in a WebView, how can I adjust the text color within a React Native WebView? <WebView source={{ html: this.props.content }}/> ...

Search in the Firestore database for documents that have a field containing a reference to another document. Once those results are found, use the reference to conduct a second query

In an attempt to optimize the query that delivers details of all events a participant has attended, I have restructured my database schema. Events with participants are now linked through a subEvent subcollection in the users collection, storing document r ...

Tips on deactivating a button after it has been clicked once within a 24-hour period and reactivating it the following day with the use of JavaScript and Angular

Is it possible to disable my button after one click per day, and then automatically re-enable it the next day once a user has entered details using the submit button? I need assistance with JavaScript or AngularJS for this functionality. ...

Associating checkbox options with an array that is void of elements

I have a series of arrays linked to checkboxes and I am trying to create a unique array based on the selected checkbox values. Here is an example of the HTML structure: <input type="checkbox" value="value1">Value 1 <input type="checkbox" value=" ...

How can I retrieve and showcase the size of each file, including images, CSS, and JS, present on a website?

Currently, my goal is to create a dashboard capable of retrieving the file size for all resources (images, javascript, css, etc.) loaded on a webpage. I aim to then further filter these resources by file type and file size in order to identify which ones c ...

Is it possible to change all text to lowercase except for URLs using .tolowercase()?

Currently, I am facing a challenge with my Greasemonkey script. The use of .tolowercase() is causing all uppercase letters to be converted to lowercase, which is disrupting URLs. I have explored alternatives like .startswith() and .endswith(), considering ...

Execute a simulated click on the Material-UI Tabbar using a programmatic approach or keyboard shortcut

In my electron/react application, I am implementing Material UI tabs in the following manner: <Tabs> <Tab label="View1" > <View1 /> </Tab> <Tab label="View2"> ...

Inserting a component within a TabPanel in Material-UI React

I am currently working on building a dashboard component utilizing material-ui tabs. Each tab should render a different component, and although it is functional, I keep encountering a console warning multiple times when the page loads. index.js:1 Warning: ...

Mastering the Art of jQuery: Easily Choosing and Concealing a Div Element

I'm currently facing challenges in removing a div upon successful AJAX completion. The issue I'm encountering is that the word "Added" appears twice after success, indicating that I am not properly selecting the two divs containing it. Any sugges ...

What is the best way to retrieve an array of objects that have a property matching another array?

In my array, I have data structured like this: array = [ { name: "john", tag: ["tag1", "tag2"] }, { name: "doe", tag: ["tag2"] }, { name: "jane", tag: ["tag2", "tag3"] } ]; My goal is to create a new array of objects that only contain elements with ...

The footers on each page are not consistent

I have noticed that two pages utilizing the same CSS are displaying differently. Check them out here: 128.48.204.195:3000 128.48.204.195:3000/formats If you look closely, you'll see that below the footer, the /formats page appears to have no extra s ...

Managing errors in React Router on the server-side

I am currently working on an isomorphic application using react-router and express. My goal is to implement custom error pages that will be displayed in case of server-side errors, rendering errors, or when a page is not found. However, I am facing difficu ...

React dependency installation problem encountered

npm install axios moment react-file-base 64 redux redux-thunk npm ERR! 404 npm ERR! 404 Note that you can also install from a npm ERR! 404 tarball, folder, http url, or git url. npm ERR! A complete log of this run can be found in: C:\Users\apa10 ...

I've noticed that every time I use the simple-encryptor npm to encrypt something, the output is always different

Can you assist me in solving this issue? var key = 'real secret keys should be long and random'; // Generating an encryptor: var encryptor = require('simple-encryptor')(key); var encryptedText = encryptor.encrypt('testing') ...

Having difficulty pinpointing and deleting an added element using jQuery or JavaScript

My current task involves: Fetching input from a form field and adding the data to a div called option-badges Each badge in the div has a X button for removing the item if necessary The issue at hand: I am facing difficulty in removing the newly appended ...

Utilizing the Onchange Event with Multiple Input Fields in Vanilla JavaScript

I'm working on a website where multiple inputs need to be created dynamically using createElement. Each input can have its own class, id, and other attributes. The main objective is to automatically calculate the overall price whenever a user adds a ...

Continual Heroku Deployment Struggles Persist during the "devDependencies Pruning" Phase

I'm running into difficulties deploying my project to Heroku and despite my best efforts, I can't seem to pinpoint the issue. The error log on Heroku shows the following message after successfully building my react app: -----> Caching build ...

Tips for maintaining the parent's width during a resize operation

I have a query: I am facing an issue with an image inside a div. The image is larger than the div, so I set its height to 100% to make it appear correctly. When I resize the image, it adjusts well and looks fine. However, when I resize the browser to make ...