I'm trying to create a function that would accept a string and split it into separate lines so that each "line" would fit into reference container without wrapping. Later I'll use this output to animate each line reveal.
Currently I'm using this library but I'm struggling with few issues, so I'm to build my own solution.
Library: https://cyriacbr.github.io/react-split-text/
https://github.com/CyriacBr/react-split-text
My issues with it:
- it triggers a rerender after height of the viewport changes ( so on mobile, thats every time a browser menu pops up )
- it measures line width based on single span width, but I'm using non monotype font, so its not accurate and causes weird issues
My idea is that I would make a component ( or a hook ), that would accept a string, and return array of lines (strings).
It would work sth like this:
- split text into words
- render each word in a ghost component, so that I would be able to measure each word by adding a ref to it
- measure container width
- group words into array of "lines" that would fit into container without wrapping.
So far I've came up with this solution:
https://codesandbox.io/s/buggy-line-splitter-c2j7b
It kinda works, but it's buggy.
Issues with my solution:
my lines are wider than they should be, text wraps but it shouldn't.
i could "fix" issue above by multiplying container width by .9, but I feel that its gonna break sooner or later.
Do you have any ideas how I could improve my solution? Thanks
////////////////////////////////////////////////
I have found the answer to my problem!
Expanding on @Will idea, there is thread with solution to the problem:
Weird issue with styles and element measurement (scrollWidth / scrollWidth) in Gatsby