malte-wessel / react-textfit

React component to fit headlines and paragraphs into elements
http://malte-wessel.github.io/react-textfit/
MIT License
474 stars 144 forks source link

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

Closed ndbroadbent closed 6 years ago

ndbroadbent commented 6 years ago

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.

denis-sokolov commented 6 years ago

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

https://github.com/malte-wessel/react-textfit/blob/11e5c15e2aed097ef9187df40b0553fff4375185/src/Textfit.js#L70-L74

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.

ndbroadbent commented 6 years ago

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:

https://github.com/malte-wessel/react-textfit/blob/11e5c15e2aed097ef9187df40b0553fff4375185/src/Textfit.js#L92-L96

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!

arist0tl3 commented 6 years ago

@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 =)