Is it possible to detect if text is exceeding its designated space and incorporate this as a condition within the code?

I've created a React component (A) that displays some text. When the text exceeds the available space, I want to display a tooltip - another component with the full text. In my CSS file, I've defined that A has the text-overflow property set to "ellipsis".

This project is implemented using JavaScript (React) and Less.

I'm curious to know if there's a way to determine if ellipses are present (indicating text overflow), and based on that, dynamically render the additional component.

Answer №1

I put together a STACKBLITZ to showcase how to conditionally add a title attribute to a div element when it is ellipsed with an overflow: hidden style.

Here is the code snippet:

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      ellipsed: false
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    this.myRef.current.innerHTML = event.target.value;
    const {scrollWidth, offsetWidth} = this.myRef.current;
    // adding 2 pixels for border
    const newEllipsed = scrollWidth - offsetWidth > 2;
    if (newEllipsed !== this.state.ellipsed) {
      this.setState(prevState => ({
        ...prevState,
        ellipsed: newEllipsed
      }));
    }
  }

  myRef = React.createRef();

  render() {
    return (
      <div>
        <textarea onChange={this.handleChange} ></textarea>
        <Hello name={this.state.name} />
        <p>
          Start editing to see some magic happen :)
        </p>
        <div id="ellipsed" 
             {...this.state.ellipsed && {title: this.myRef.current.innerHTML}}
             ref={this.myRef}></div>
      </div>
    );
  }
}

Answer №3

Just like @sulten-h pointed out, there is a question on Stack Overflow that covers a similar topic to yours. However, I think your question deserves attention especially in the context of React.

In the code example below, I demonstrate how you can apply the solution from that question to a React application. Keep in mind that there are other ways to solve this problem as well.

You can view the implementation here: https://codesandbox.io/embed/text-overflow-bomo3

Take a look and see if it fits your requirements.

I hope this information proves helpful to you.

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

CodeMirror's styling becomes inconsistent during state changes or component re-renders in Next.js. Although everything appears to function correctly during development, issues arise in production

In my current Nextjs project, I am utilizing react-codemirror version ^4.20.2. While everything works perfectly in the development environment, once I deploy the app on Vercel, the Codemirror component experiences appearance and styling issues upon re-rend ...

retrieving data from a php file using ajax for a post request

Utilizing ajax, I have invoked the page search.php: function search(){ var title=$("#search").val(); if(title!=""){ $.ajax({ type:"post", url:"sear ...

Encountered an unusual IP address while attempting to start yarn - EADDRNOTAVAIL

Recently, I installed OpenSUSE on my laptop and decided to try out a new React application. However, when I ran the commands from the create-react-app site: npx create-react-app my-app cd my-app yarn start I encountered an issue in my terminal with the f ...

Having trouble retrieving a hidden value in JavaScript when dealing with multiple records in a Coldfusion table

In this table, there is a column that allows users to select a predicted time. <cfoutput query="getReservations"> <tbody> <td><input class="form-control predicted" name="predicted" id="ReservaTempoPrevisto" placeholder= ...

Obtaining the Immediate ID of a Widget using JQuery

I currently have the following setup: <div id="dualList"></div> I created a plugin but stripped it down for testing purposes. I am encountering difficulties with the plugin not displaying the ID of the div. <script> (function($) { ...

problem with saving session data

I am attempting to access data from another page using session storage. On my initial page, named home.html function go_to_faq(qnum){ window.open('FAQ.html', '_blank'); sessionStorage.setItem('key2', qnum); } <a s ...

Choosing a menu option with jQuery

Can someone help me with making a menu option selected in HTML? Here is my code: <ul class="ca-menu"> <li> <a href="#"> <span class="ca-icon"><img src="images/home.png" ...

Encountering the error message "Unable to access property 'addEventListener' of null while trying to manipulate innerHTML"

Currently, I am utilizing innerHTML to include certain elements and a wrapper around them. for (i = 0; i < arr.length; i++) { b.innerHTML += "<div class='wrapper'><div class='col-4'>" + arr[i].storeID + "</div> ...

Retrieving information through callback functions

A function I developed checks a list of tags that are submitted to it, sorting the good ones into a "good" array and the bad ones into a "bad" array. This process occurs within a callback, allowing the rest of my code to continue once complete. However, I ...

The use of `await` within a loop may not function as anticipated when the code is being run through Puppeteer, yet it functions flawlessly when executed in the browser's console

Currently, I am assessing the functionality of the codeToBeEvaluated function within a browser environment using puppeteer. Within codeToBeEvaluated, there is a while loop designed to trigger an alert (referenced as LINE B) every 10 seconds. The issue ari ...

The embedded content within the iframe is failing to display on the screen even after verifying the onload event using

Our team is working on creating an HTML game that incorporates abobe edge for animations within iframes. To enhance user experience, we are attempting to preload the iframes before removing the 'loading screen' to prevent users from seeing blank ...

What could be causing my image not to show up on ReactJS?

I'm new to ReactJS and I am trying to display a simple image on my practice web app, but it's not showing up. I thought my code was correct, but apparently not. Below is the content of my index.html file: <!DOCTYPE html> <html> & ...

Is it possible to target all children with CSS3 if a certain number of children are present?

I've been racking my brain trying to select all children if there are x or more children present. I want to be able to select all child elements if there are at least x children. So far, I've managed to target all children when there are exactl ...

Is there a way to convert an array into a single comma-separated value using parameters?

Is there a way to parameterize an array as a single name-value pair that is comma separated? I have tried using jQuery $.param, but it creates a parameter for each value in the array instead of just one. Unfortunately, it seems that there is no option or s ...

jQuery doesn't seem to function properly upon initial click

Working with Rails and attempting to implement an ajax bookmark icon functionality. When clicking for the first time, the request is sent but the image does not change; however, subsequent clicks work as expected (request sent and image changes). This is ...

Embellishing Your Website with Unique Cursor Styles

Looking to add personalized cursors to my website using asp.net 4.0. On my master page, I aim to set a custom cursor as the default for the entire site and have different custom cursors for all links. Is this achievable? ...

JavaScript challenge at an electronics store coding competition

Hello, I recently attempted a code challenge but unfortunately only passed 9 out of the 16 tests. I am seeking feedback on what may be going wrong in my code. The problem link can be found here: function getMoneySpent(keyboards, drives, budget) { l ...

React Functional Component not working properly following package update

After a 4-month hiatus from programming, I decided to update this project using npm but encountered issues with all my stateless functions. interface INotFoundPageContainerProps { history: any; } class NotFoundPag ...

The HTML page abruptly cuts off halfway without allowing the user to scroll further

As a newcomer to the world of html and css, I am attempting to construct a reporting page that will showcase various script outputs. However, I am running into an issue where only half of my page is displayed with a scroll bar, whereas I would like the o ...

"Using the power of jQuery to efficiently bind events to elements through associative

I am attempting to link the same action to 3 checkboxes, with a different outcome for each: var checkboxes = { 'option1' : 'result1', 'option2' : 'result2', 'option3' : 'result3', }; ...