malte-wessel/react-textfit

Dynamic text can shrink, but font-size doesn't seem to increase when text changes

ndbroadbent opened this issue · 3 comments

Maybe related to #38

I have a div with some dynamic text that the user enters. When the text is too long, react-textfit does a good job of shrinking it to fit. But if the text becomes shorter, it does not increase the size again. Is this the expected behavior?

My workaround is set a key, like <Textfit key={text}>. This means that React will use a new Textfit component whenever the text changes, so it always recalculates the correct size.

But it might be good if react-textfit had an option for this, even if it is not the default behavior.

This should absolutely happen using our code that listens to componentDidUpdate lifecycle event. If it doesn’t, I suppose it’s a bug.

componentDidUpdate(prevProps) {
const { ready } = this.state;
if (!ready) return;
if (shallowEqual(this.props, prevProps)) return;
this.process();

The workaround with key is absolutely a very good workaround.

I don’t have the ability to debug this problem, but if you figure out why that code does not trigger a resize, a PR is very welcome.

Hello, thanks for your help! I could see that this.process() is being called when I change the text, so that part was working.

I looked at the code and found my problem here:

const el = this._parent;
const wrapper = this._child;
const originalWidth = innerWidth(el);
const originalHeight = innerHeight(el);

The originalHeight of the _parent element kept getting smaller and smaller. I fixed the issue by adding this to my own SCSS:

    & > div {
      width: 100%;
      height: 100%;
    }

This sets width and height to 100% for the _parent div, so the originalHeight doesn't change any more.

(In my case, I'm showing text inside a box with fixed width and height values.)

Thanks again!

@ndbroadbent

My workaround is set a key, like <Textfit key={text}>. This means that React will use a new Textfit component whenever the text changes, so it always recalculates the correct size.

Thanks for this. Was pulling my hair out with the shrinking text =)