Linda Langerová
Linda Langerová

Reputation: 101

Is there a way to find out if the text is overflowing and use it as a condition in code?

I have a react component (A) that renders some text. If the text overflows, I'd like to show tooltip - another component with full text. In css file, I set that A has text-overflow property set as "ellipsis".

Using JS (react) and less.

I would like to know if there is a possibility to find out if there are ellipses (the text overflows) and according to that just render also the other component.

Upvotes: 2

Views: 6525

Answers (3)

guzmonne
guzmonne

Reputation: 2540

As @sulten-h mentioned, this question is similar to the one you are asking now. Nonetheless, I feel like yours bears attention given that it's in the context of React.

On the following example, I use the answer to that question on a React application. It's by no means the only solution.

https://codesandbox.io/embed/text-overflow-bomo3

Check it out and see if it meets your needs.

I hope it helps.

Upvotes: 0

Andriy
Andriy

Reputation: 15442

I created a STACKBLITZ demonstrating conditionally adding title attribute to div element. I assume that ellipsed element has overflow: hidden style.

the code:

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;
    // add 2 pixels due to 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>
    );
  }
}

Upvotes: 2

Ricardo Gonzalez
Ricardo Gonzalez

Reputation: 1879

You can use this style in your tag element that contains the text:

text-overflow: ellipsis;

https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow

Upvotes: 0

Related Questions