2

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.

3 Answers3

2

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>
    );
  }
}
Andriy
  • 14,781
  • 4
  • 46
  • 50
0

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

Ricardo Gonzalez
  • 1,827
  • 1
  • 14
  • 25
0

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.

Richie Thomas
  • 3,073
  • 4
  • 32
  • 55
guzmonne
  • 2,490
  • 1
  • 16
  • 22