3

I'm currently trying to make my React Native application based on Expo without dropping down to native dependencies. I'm wondering if there is a way to measure text (down to the pixel) so I can make some intelligent choices about layouts without ending up with elides or weird wrapping.

Basically I'd like to be able to do something like:

//Pseudo Code
class SomeScreen extends React.Component {
  //returns a height that fits the width without wrapping
  fitToWidth(text, width) { 
    //I don't have a framework for this in Expo
  }
  render() {
    <View>
      <MyText fontSize={fitToWidth('SomeString', 375)} value='Some String' />
    </View>
  }
}

It would be really nice to have this run in Expo due to the ease of testing and I'm hoping someone has an idea of how to achieve this. There are some libraries that I can drop down into, but it requires ejecting out of the Expo build process which means it is no longer portable.

I realize there's a lot more to do to be able to render this, but I can already figure out the width and height of views and I'm hoping I can find a way to measure text to select a font based on the screen size rather than trying to depend on points.

Daniel B. Chapman
  • 4,647
  • 32
  • 42

1 Answers1

0

You need to attach the onLayout event to your view. Once RN calculates that, you get the dimensions back.

https://facebook.github.io/react-native/docs/view.html#onlayout

sebastianf182
  • 9,844
  • 3
  • 34
  • 66
  • i think what op wants is a dynamic `fontSize` that will fit one line perfectly on any device (with no ellipses) – Bill Nov 06 '17 at 01:04
  • Good point. Well, attaching the onLayout into the parent view could let you choose the fontSize dynamically. Let's see what OP says. – sebastianf182 Nov 06 '17 at 01:06
  • @Bill You're correct, I'm trying to calculate a font that will fall inside the bounds correctly. I'll dig into this and see if there's a way to do it backwards (calculating the onLayout size) efficiently. – Daniel B. Chapman Nov 06 '17 at 23:54
  • @sfrantini thanks for the answer, I'll see if I can make this work. – Daniel B. Chapman Nov 06 '17 at 23:54
  • @DanielB.Chapman Well, if you want the width of the device you can use https://facebook.github.io/react-native/docs/dimensions.html. If you want the width of the current view, then I guess you'll have to play with onLayout. – sebastianf182 Nov 06 '17 at 23:57